While following the coursera Scala course my Odersky, I implemented the below List example:
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")
}
Then I tried creating diff example and most of them worked except when I wanter to create a sample like 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))
Can someone please help me to understand what I am doing wrong?