How does a system like Scala know that cons + Nil is comprehensive?

I just wrote this function, wondering what would happen if I omitted the Nil case and noticed that scalac was giving me a warning:

def printList[String](list: List[String]) {
    list match {
        case head :: tail => {
            println(head)
            printList(tail)
        }
        //case Nil => println("Done")
    }
}

Warning: match may not be exhaustive. It would fail on the following input: Nil

I'm having problems with what's happening here. I get a general idea of ​​pattern matching by recursive data type until you run out of cases, but it is not clear to me how this relates to a system like Scala. In particular, I look at the source code of the Scala standard library and wonder:

  • Where exactly in the Scala code does the idea arise that the base register is needed to complete the matching operator for an instance of the List class? One could, of course, imagine a type of algebraic data that “just continues” without a basic case.
  • scala.collection.immutable.Nil, , List?
+4
2

List . , List sealed, :

sealed abstract class List[+A] ...
case object Nil extends List[Nothing] { ... }
final case class ::[B](override val head: B, private[scala] var tl: List[B]) extends List[B] { ... }

Scala , , . 8.4 Scala :

, , , , .. MatchError .

+2

, . List sealed abstract class , Nil :: (, ). - sealed. , , List, , List.

sealed , List, , , , .

, , , :: . , case:

case class Foo(a: String, b: Int)

x match {
  case Foo(a, b) => //...
}

, case , :

x match {
  case a Foo b => //...
}

, :

list match {
        case ::(head, tail) => {

, , , ::. , , , Nil .

+7

All Articles