特征体内的 Scala 类型匹配函数

Scala Type matching function inside a trait body

我是 Scala 的新手,正在阅读本书 (Function Programming in Scala)。其中一项练习涉及复制 Option 特征及其功能。但是,我在 REPL 中编译我的解决方案时遇到问题。

sealed trait Nullable[+A] {

    def get[B >: A](default: => B) : B = this match {
        case Value(v) => v
        case Null => default
    }
}
case class Value[+A](value: A) extends Nullable[A]
case object Null extends Nullable[Nothing]

REPL 错误详情:

error: constructor cannot be instantiated to expected type;
found   : Value[A(in class Value)]
required: Nullable[A(in trait Nullable)]
             case Value(v) => v

error: pattern type is incompatible with expected type;
found   : Null.type
required: Nullable[A]
             case Null => default

基于这些错误,我有一种挥之不去的感觉,即编译器无法推断出 this 的类型(进行模式匹配)是 Nullable.

我已经在网上试过这段代码 Scala utility,它似乎可以编译 运行。我能看到的唯一区别是在线工具使用的是 Scala 版本 2.10.3 而我 运行ning 2.11.7

所以我不确定这是否是环境问题,或者我是否需要在这里帮助 Scala 编译器。我也尝试编译本书作者的 answer,但我得到了同样的错误。

如有任何帮助,我们将不胜感激。

发布答案以防其他人遇到类似问题。

使用 REPL :paste 命令加载 .scala 文件,而不是 :load 命令。

感谢@noah 和@jwvh 的帮助。