【发布时间】:2018-12-05 20:02:18
【问题描述】:
我正在尝试在 trait 中定义一个 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()
^
有人可以建议吗?
【问题讨论】:
-
为了您的信息,我从 scala REPL 加载源文件如下:
scala> :load stream.scala -
.toList之后的这个()不属于那里,但除此之外,它似乎编译得很好?至少,它可以在 2.12.5 - 2.12.7 版本中编译。