Match tuple to null

I do not understand why the following case does not match. Zero must be an Any instance, but it does not match. Can someone explain what is happening?

val x = (2, null) x match { case (i:Int, v:Any) => println("got tuple %s: %s".format(i, v)) case _ => println("catch all") } prints catch all 

Thanks.

+6
null scala pattern-matching tuples
source share
4 answers

This is exactly as indicated.

 Type patterns consist of types, type variables, and wildcards. A type pattern T is of one of the following forms: * A reference to a class C, pC, or T#C. This type pattern matches any non-null instance of the given class. 

Interestingly, such significance was due to the fact that null is a member of Any. This is a member of any type, but AnyVal and Nothing.

+9
source share

Have you tried v placeholder for anything?

 val x = (2, null) x match { case (i:Int, v) => println("got tuple %s: %s".format(i, v)) case _ => println("catch all") } 
+6
source share

What is indicated (Scala Ref. 2.7, section 8.2):

A reference to a class C, pC, or T # C. This type models any non-zero instance of this class. Note that the class prefix, if given, is relevant for defining class instances. For example, the pC pattern matches only examples of C classes that were created using the p path as a prefix.

+3
source share

I just guess since I am not a scala expert, but according to the documentation for the Any class in scala, I think that since null is not an object, it is not the result of Any and, as such, does not match the first case specified.

Adding sample code below. It prints "something else" at startup.

 val x = (2, null) x match { case (i:Int, v:Any) => println("got tuple %s: %s".format(i, v)) case (i:Int, null) => println("something else %s".format(i)) case _ => println("catch all") } 

After additional research, it seems that zero should match any value of the documentation , says that it extends AnyRef, which extends Any.

EDIT: Like everyone else. The first case does not correspond to a zero value. It is listed in the documentation.

+1
source share

All Articles