我试图在特征中定义一个toList
方法,如下所示:
sealed trait Stream[+A] {
def toList: List[A] = this match {
case Empty => List()
case Cons(h, t) => h()::t().toList()
}
}
case object Empty extends Stream[Nothing]
case class Cons[+A](h: () => A, t: () => Stream[A]) extends Stream[A]
object Stream {
def cons[A](hd: => A, tl: => Stream[A]): Stream[A] = {
lazy val head = hd
lazy val tail = tl
Cons(() => head, () => tail)
}
def empty[A]: Stream[A] = Empty
def apply[A](as: A*): Stream[A] =
if (as.isEmpty) empty else cons(as.head, apply(as.tail: _*))
}
我收到以下编译错误:
stream.scala:16: error: pattern type is incompatible with expected type;
found : Empty.type
required: Stream[A]
case Empty => List()
^
stream.scala:17: error: constructor cannot be instantiated to expected type;
found : Cons[A(in class Cons)]
required: Stream[A(in trait Stream)]
case Cons(h, t) => h()::t().toList()
^
有人可以建议吗?
答案 0 :(得分:3)
您看到的错误来自REPL。 REPL中的每个完整语句都打包在一个对象中,以便它可以产生和报告中间值:res0
,res1
等。
在:load
文件中,就好像您分别键入每行一样,但是如果您复制/粘贴:pa
,则代码会在REPL中起作用(修复{{ 1}}问题)。
另一个选择是将所有代码包装到外部()
中。然后,当您object
将文件编译为一个单元而不是单独的对象和类时。