我是新來的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'。這可能不是你想要的。 –