Wrapping null-returning method in Java with Option in Scala? Wrapping null-returning method in Java with Option in Scala? java java

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] = Nonescala> Option(3)   res5: Option[Int] = Some(3)


The Option object has an applymethod 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 = nullval option: Option[Int] = Option(nullValueInteger)println(option)  // Doesn't work - zero value on conversionval nullStringValue : String = nullval optionString: Option[String] = Option(nullStringValue)println(optionString) // Works - None value