The factory method for Option
will turn a null
into a None
:
scala> val os1: Option[String] = Option(null)
os1: Option[String] = None
Addendum
I may have misunderstood your question...
If you restrict its scope judiciously, you can use an implicit conversion:
scala> implicit def nullable2Option[T >: Null](t: T): Option[T] = if (t == null) None else Some(t)
warning: there were 1 feature warnings; re-run with -feature for details
nullable2Option: [T >: Null](t: T)Option[T]
scala> val os2: Option[String] = "foo"
os2: Option[String] = Some(foo)
scala> val nullS: String = null
nullS: String = null
scala> val os3: Option[String] = nullS
os3: Option[String] = None
This will work any time there's available type information for the compiler to use to drive the attempt to bridge a value of a nullable type to an Option
. E.g., when calling a method (where the types are always explicit).