seasick seasick - 1 month ago 6
Scala Question

Modifying the list class

I'm working through Functional programming in Scala and the first few chapters define this type of data structure:

sealed trait List[+A]
case object Nil extends List[Nothing]
case class Cons[+A](head: A, tail: List[A]) extends List[A]


When I try to define a linked list like this; it works as expected:

val nums: List[Int] = Cons(1, Cons(2, Cons(3, Nil)));


I am however trying to define a linked list like this, but I get a compilation error (Expression of type scala.collection.immutable.List[Int] doesn't conform to expected type List[Int]:

val nums: List[Int] = List[Int](1, 2, 3)


My question is - 1) Does declaring the data structure modify the internal class of List? 2) Why can't the second structure be used?

Answer

1) Does declaring the data structure modify the internal class of List?

No.

2) Why can't the second structure be used?

You are calling the apply method of the List object. The only object named List that is in scope is the scala.collection.immutable.List object and its apply method returns an instance of scala.collection.immutable.List. However, you have declared nums to be of type List[Int], not scala.collection.immutable.List[Int], therefore the two types are not compatible.

You need to write your own List object, for example like this:

object List {
  def apply[A](elements: A*): List[A] = 
    if (elements.isEmpty) Nil else Cons(elements.head, apply(elements.tail :_*))
}