在遵循我的 Odersky 的 coursera Scala 课程时,我实现了以下列表示例:
trait List[T] {
def isEmpty : Boolean
def head : T
def tail : List[T]
override def toString() = if(this.isEmpty) "" else "{" + head + tail + "}"
}
class Cons[T](val head: T, val tail: List[T]) extends List[T] {
def isEmpty : Boolean = false
}
class Nil[T] extends List[T] {
def isEmpty : Boolean = true
def head : Nothing = throw new NoSuchElementException("Nil.head")
def tail : Nothing = throw new NoSuchElementException("Nil.tail")
}
然后我尝试创建 diff 示例,除了我想创建像 List(4,5, List(2,3)) 这样的示例之外,它们中的大多数都可以工作。
val list1 = new Cons(4, new Cons(5, new Nil)) //worked
val list = new Cons(1, new Cons(2, new Cons(3, new Nil))) //worked
val mList = new Cons(list1, new Cons(list, new Nil)) //worked
val nList = new Cons(4, new Cons(list, new Nil)) // DID NOT WORK
// <console>:11: error: type mismatch;
// found : Cons[Cons[Int]]
// required: List[Any]
// Note: Cons[Int] <: Any, but trait List is invariant in type T.
// You may wish to define T as +T instead. (SLS 4.5)
// val nList = new Cons(4, new Cons(list, new Nil))
有人可以帮我理解我做错了什么吗?