scala 选项 getOrElse 类型不匹配错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13186063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:41:28  来源:igfitidea点击:

Option getOrElse type mismatch error

scalaimplicit-conversiontype-mismatch

提问by sndyuk

Why does this code raise a type mismatch error in Scala 2.9.2? I expected that getOrElsereturns type Stringbut actually it returns java.io.Serializable:

为什么这段代码会在 Scala 2.9.2 中引发类型不匹配错误?我期望getOrElse返回类型String但实际上它返回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("")
                                             ^

This is OK:

还行吧:

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)

回答by Rex Kerr

It's an unwanted case of incomplete tree traversal. The signature of getOrElseallows type widening, so when it realizes that Stringis 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.

这是不完整的树遍历的一种不需要的情况。的签名getOrElse允许类型扩展,因此当它意识到String不是Option[String]它时,它首先尝试在 上填充不同的类型归属getOrElse,即Serializable。但是现在它已经"a".getOrElse[Serializable]("")并且卡住了 - 我猜它没有意识到问题是在检查隐式之前使类型过于笼统。

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.

现在打字机不会沿着 let's-widen 路径徘徊,而是找到隐含的。