Monday, January 11, 2010

Matching Nulls

As a bit of explanation of one of the techniques in Regex Matching this topic reviews matching nulls.

  1. // No surprise _ matches everything
  2. scala> null match { case _ => println("null") }
  3. null
  4. // again null matches null
  5. scala> null match { case null => println("null") }
  6. null
  7. // a is bound to anything including null
  8. scala> null match { case a => println("matched value is: "+a) }
  9. matched value is: null
  10. scala> val a:String = null
  11. a: String = null
  12. // basically same as last example
  13. scala> a match {case a => println( a + " is null")}          
  14. null is null
  15. // Any matches any non-null object
  16. scala> null match {                                                
  17.      | case a:Any => println("matched value is: "+a)               
  18.      | case _ => println("null is not Any")
  19.      | }
  20. null is not Any
  21. scala> val d:String = null                             
  22. d: String = null
  23. // In fact when matching null does not match any type
  24. scala> d match {                                       
  25.      | case a:String => println("matched value is: "+a)
  26.      | case _ => println("no match")                   
  27.      | }
  28. no match
  29. scala> val data:(String,String) = ("s",null)         
  30. data: (StringString) = (s,null)
  31. // matching can safely deal with nulls but don't forget the catch all
  32. // clause or you will get a MatchError
  33. scala> data match {                                  
  34.      | case (a:String, b:String) => "shouldn't match"
  35.      | case (a:String, _) => "should match"          
  36.      | }
  37. res10: java.lang.String = should match
  38. // again null is all objects but will not match Any
  39. scala> data match {                            
  40.      | case (a:String, b:Any) => "shouldn't match"   
  41.      | case (a:String, _) => "should match"       
  42.      | }
  43. res12: java.lang.String = should match

3 comments:

  1. This gives the impression that "Any" is special when dealing with nulls, but it is not. Whatever type you use, it won't match nulls.

    ReplyDelete
  2. a good point. I updated the post to show the similar case matching to a string. Hopefully that potential misunderstanding is cleared up

    ReplyDelete
  3. Daniel: True. However the opposite is not true. For example if you have a tupple with one value either null or a String then the string will produce an error when matched with null:

    error: pattern type is incompatible with expected type;
    found : String
    required: Null

    So matching Any seem the better option.

    ReplyDelete