Wrapping null-returning method in Java with Option in Scala?
The Option
companion object's apply
method serves as a conversion function from nullable references:
scala> Option(null)
res4: Option[Null] = None
scala> Option(3)
res5: Option[Int] = Some(3)
The Option
object has an apply
method that does exactly that:
var myOptionalString = Option(session.get("foo"));
Notice that when working with Java objects it won't work as expected:
val nullValueInteger : java.lang.Integer = null
val option: Option[Int] = Option(nullValueInteger)
println(option) // Doesn't work - zero value on conversion
val nullStringValue : String = null
val optionString: Option[String] = Option(nullStringValue)
println(optionString) // Works - None value