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

1 comment:

  1. I added an implicit in my top package that add a nullSafe method to any implicit def any2NullSafe[A](value: A) = new {
    def nullSafe: Option[A] = NullSafe[A](value)

    /**
    * When null returns the OrElse blk
    */
    def whenNull(whenNullResult: => A): A = {
    if (value == null) {
    whenNullResult
    } else {
    value
    }
    }

    def notNull[B](whenNotNull: (A) => B): B = {
    if (value == null) {
    null.asInstanceOf[B]
    } else {
    whenNotNull(value)
    }
    }
    }

    ReplyDelete