Scala的@运营商做什么?
例如,在Scala的博客文章Formal Language Processing,第2部分中有类似的东西
case x @ Some(Nil) => x
Run Code Online (Sandbox Code Playgroud) 我正在遵循Scala 和方法上的模式匹配和功能组合教程.有这样一个例子:composeandThen
scala> def addUmm(x: String) = x + " umm"
scala> def addAhem(x: String) = x + " ahem"
val ummThenAhem = addAhem(_).compose(addUmm(_))
Run Code Online (Sandbox Code Playgroud)
当我尝试使用它时,我收到一个错误:
<console>:7: error: missing parameter type for expanded function ((x$1) => addAhem(x$1).compose(((x$2) => addUmm(x$2))))
val ummThenAhem = addAhem(_).compose(addUmm(_))
^
<console>:7: error: missing parameter type for expanded function ((x$2) => addUmm(x$2))
val ummThenAhem = addAhem(_).compose(addUmm(_))
^
<console>:7: error: type mismatch;
found : java.lang.String
required: Int
val ummThenAhem = addAhem(_).compose(addUmm(_))
Run Code Online (Sandbox Code Playgroud)
但是,这有效:
val ummThenAhem = …Run Code Online (Sandbox Code Playgroud) 我有一个Scala案例类
case class Example(name: String, number: Int)
Run Code Online (Sandbox Code Playgroud)
和一个伴侣
object Example {
implicit object ExampleFormat extends Format[Example] {
def reads(json: JsValue) = {
JsSuccess(Example(
(json \ "name").as[String],
(json \ "number").as[Int]))
}
def writes(...){}
}
}
Run Code Online (Sandbox Code Playgroud)
它将JSON转换为Scala对象.
当JSON有效时(即{"name":"name","number": 0}它工作正常.但是,当number引用时{"name":"name","number":"0"}我得到一个错误:validate.error.expected.jsnumber.
有没有一种方法,以隐式转换String到Int在这种情况下(假设号码是有效的)?