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.
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.
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.
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 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With