I'm new in Scala and I'm reading fp in Scala. There is an example code in this book and I type this into Idea:
sealed trait mList[+A]
case object mNil extends mList[Nothing]
case class Cons[+A] (head:A, tail:mList[A]) extends mList[A]
object mList {
def sum(ints: mList[Int] ): Int = ints match {
case mNil => 0
case Cons(h, t) => h + sum(t)
}
def apply[A](as: A*): mList[A] =
if (as.isEmpty) mNil
else Cons(as.head, apply(as.tail:_*))
}
Then I get a warning from Idea that case Cons(h, t)
is unreachable.
I'm sure in this book case Nil
comes before case Cons
. But when I run the code this way I always get sum=0.
So should I swap the orders of the two cases?