问题描述
为什么此代码会在Scala 2.9.2中引发类型不匹配错误?我期望getOrElse
返回类型String
,但实际上它返回java.io.Serializable
:
Why does this code raise a type mismatch error in Scala 2.9.2? I expected that getOrElse
returns type String
but actually it returns java.io.Serializable
:
scala> implicit def StringToOption(s:String) = Option(s)
StringToOption: (s: String)Option[String]
scala> "a".getOrElse("")
res0: String = a
scala> var opt:Option[String] = "a".getOrElse("")
<console>:8: error: type mismatch;
found : java.io.Serializable
required: Option[String]
var opt:Option[String] = "a".getOrElse("")
^
这可以:
scala> implicit def StringToOption(s:String): Option[String] = Option(s)
StringToOption: (s: String)Option[String]
scala> var b:Option[String] = "a".getOrElse("") toString
b: Option[String] = Some(a)
推荐答案
这是不完整的树遍历的不良情况. getOrElse
的签名允许类型扩展,因此,当意识到String
不是Option[String]
时,它首先尝试在getOrElse
上填充不同的类型名称,即Serializable
.但是现在它有了"a".getOrElse[Serializable]("")
并被卡住了-我想我没有意识到问题在于在检查隐式类型之前,该类型太笼统了.
It's an unwanted case of incomplete tree traversal. The signature of getOrElse
allows type widening, so when it realizes that String
is not Option[String]
it first tries to fill in a different type ascription on getOrElse
, i.e. Serializable
. But now it has "a".getOrElse[Serializable]("")
and it's stuck--it doesn't realize, I guess, that the problem was making the type too general before checking for implicits.
一旦意识到问题,就可以解决:
Once you realize the problem, there's a fix:
"a".getOrElse[String]("")
现在,打字员无需沿着让我们扩大"的路径徘徊,而可以找到隐式内容.
Now the typer doesn't wander down the let's-widen path, and finds the implicit.
这篇关于选项getOrElse类型不匹配错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!