Option getOrElse type mismatch error

前端 未结 1 1730
北荒
北荒 2020-12-30 01:58

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.

相关标签:
1条回答
  • 2020-12-30 02:25

    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.

    0 讨论(0)
提交回复
热议问题