Scala: Strange MatchError when not accepting a tuple with zeros

Can anyone have a good understanding of Scala to explain why this works:

scala> Tuple2[String,String]("w3wre", "werffd")
res0: (String, String) = (w3wre,werffd)

scala> val (s1:Any, s2:Any) = Tuple2[String,String]("w3wre", "werffd")
s1: Any = w3wre
s2: Any = werffd

But not that?

scala> Tuple2[String,String]("w3wre", null)
res1: (String, String) = (w3wre,null)

scala> val (s1:Any, s2:Any) = Tuple2[String,String]("w3wre", null)
scala.MatchError: (w3wre,null) (of class scala.Tuple2)
    at .<init>(<console>:9)
    at .<clinit>(<console>)
...

(Clearly, Any-type may contain nulls:

scala> val n:Any = null
n: Any = null

scala> val n:Any = null.asInstanceOf[String]
n: Any = null

)

?

+4
source share
1 answer

The language specification clearly suggests that such type patterns do not match null( 8.2 Type Patterns , focus):

Sample templates consist of types, type variables, and wildcards. A sample T template has one of the following forms:

  • A reference to a class C, pC, or T # C. This type of template matches any non-empty instance of this class.

, , null.

+5

Source: https://habr.com/ru/post/1598359/


All Articles