Showing posts with label null. Show all posts
Showing posts with label null. Show all posts

Friday, January 15, 2010

More on Null to Option Conversion

I have seen requests for a simpler way of dealing with nulls than Option(x) so here are a couple ideas:

Note: This only works with Scala 2.8+

  1. // create an alias from Option.apply to ?
  2. scala> import Option.{apply => ?} 
  3. import Option.{apply=>$qmark}
  4. scala> ?(null)
  5. res0: Option[Null] = None
  6. scala> ?(3)
  7. res1: Option[Int] = Some(3)
  8. scala> ?(3).getOrElse(10)
  9. res2: Int = 3
  10. scala> ?(null).getOrElse(10)
  11. res3: Any = 10
  12. // create an implicit conversion to Option
  13. scala> implicit def toOption[T](x:T) : Option[T] = Option(x)
  14. toOption: [T](x: T)Option[T]
  15. scala> 3 getOrElse (10)
  16. res4: Int = 3
  17. scala> val i:String = null
  18. i: String = null
  19. scala> i getOrElse "hi"
  20. res6: String = hi

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