2010-08-27 18 views
6
List(1,2) match { 
    case List(1,_) => println("1 in postion 1") 
    case _ => println("default") 
} 

compila/funziona bene. Così fannoscala lista partita

List(1) match ... 
List(3,4,5) match ... 

ma non

List() match ... 

che si traduce nella seguente errore

found : Int(1) 
required : Nothing 
      case List(1,_) => println("1 in postion 1") 

Perché Lista() tenta di abbinare List (1, _)?

risposta

6

Quando si scrive List(), il tipo desunto è Nothing, che è sottotipo a tutto.

Quello che succede è che Scala dà un errore quando provi le partite impossibili. Ad esempio, "abc" match { case 1 => } genererà un errore simile. Allo stesso modo, poiché List(1, _) può essere determinato staticamente per non corrispondere mai a List(), Scala restituisce un errore.

2

Forse perché ...

scala> implicitly[List[Nothing] <:< List[Int]] 
res3: <:<[List[Nothing],List[Int]] = <function1> 

scala> implicitly[List[Int] <:< List[Nothing]] 
<console>:6: error: could not find implicit value for parameter e:<:<[List[Int],List[Nothing]] 
     implicitly[List[Int] <:< List[Nothing]] 
+4

Ciò significa che 'List [Int]' è coercibile a 'List [Nothing]' ma viceversa non è possibile. – missingfaktor

12

List() è di tipo List[Nothing]. Se usi List[Int]() funzionerà come previsto.

(In generale, i tipi sono restrittivi come possono eventualmente essere,. Poiché avete fatto una lista con niente in esso, il tipo più restrittivi-possibile Nothing si utilizza invece Int come desiderato)