我是新来的Scala,我正在阅读Scala书中的函数式编程,在他们的一个练习中,我得到了两个编译错误,我不明白为什么我得到那些。 我得到下面的代码下面的两个错误:错误:构造函数不能实例化到预期的类型
error: value toList is not a member of Chapter5.Stream[Int]
val list : List[Int] = st.toList
^
Stream.scala:22: error: constructor cannot be instantiated to expected type;
found : Chapter5.Cons[A]
required: Chapter5.Stream.type
case Cons(h,t) => h() :: t().toList
^
two errors found
这是特质和同伴对象:
package Chapter5
sealed trait Stream[+A]
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: _*))
}
def toList[A]: List[A] = this match{
case Cons(h,t) => h() :: t().toList
case _ => List()
}
}
当我尝试调用toList以下方式,我也得到一个错误:
package Chapter5
object Main {
def main(args : Array[String]) = {
val arr = Array(1,3,4,6)
val st : Stream[Int] = Stream.apply(arr : _*)
val list : List[Int] = st.toList
}
}
我不都不懂这些错误,对于第一种情况:很显然,我定义对象的toList方法。对于第二个Cons扩展了Stream特征,所以我不明白为什么我不能使用这样的模式匹配。
你定义的同伴对象和匹配'里面的方法toList',它是伴侣的'Stream.type'。这可能不是你想要的。 –