I'm trying to recurse over a list like this (which works):
def sumList(lst: List[Int]): Int = lst match {
case Nil => 0
case n :: rest => n sumList(rest)
}
However, I don't understand why base case is Nil
, not List(Nil)
.
(I've seen in some answers that Nil
represents empty list but:
scala> List(Nil) == Nil
val res0: Boolean = false
)
CodePudding user response:
Nil
does not represent a missing value or null
, it is a value that represents an empty list. It can equivalently be expressed List()
. List(Nil)
is a list that contains an empty list.
CodePudding user response:
val x = List()
val y = Nil
println(x == y) //true
In some cases, you must write the type (e.g., Nil: List[Int]) when writing Nil.