Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Can you use null in Scala?

null is the value of a reference that is not referring to any object. It can be used as a replacement for all reference types — that is, all types that extend scala.

How do you check for nulls in Scala?

Similarly, to check for a null reference you can do this: val resource: Option[Resource] = Option(JavaLib. getResource()) if (resource. isEmpty) { // resource is `None` type.

Which data type does Scala use instead of null for optional values?

In Scala, using null to represent nullable or missing values is an anti-pattern: use the type Option instead. The type Option ensures that you deal with both the presence and the absence of an element. Thanks to the Option type, you can make your system safer by avoiding nasty NullPointerException s at runtime.

Is using null in Scala a good practice?

As a word of caution (and balance), the Twitter Effective Scala page recommends not overusing Option , and using the Null Object Pattern where it makes sense. As usual, use your own judgment, but try to eliminate all null values using one of these approaches.


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 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 = 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