【发布时间】:2016-04-14 15:29:45
【问题描述】:
我是 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 而我运行的是 2.11.7
所以我不确定这是环境问题还是我需要在这里帮助 Scala 编译器。我还尝试从本书作者那里编译answer,但我得到了同样的错误。
任何帮助将不胜感激。
【问题讨论】:
-
当使用 repl 使用
:paste输入多行 scala 代码时,应该可以解决您的问题。 -
是的,@Noah 是对的。 REPL (2.11.7) 在作为块插入时编译它就好了(即
:pa)。 -
如果我使用
:load命令加载 .scala 文件,这是否仍然适用? -
@Noah 没关系。刚刚试了一下,效果很好!为此干杯!
标签: scala pattern-matching traits