Something like
def option[T](v: T): Option[T] = if (v == null) None else Some(v)
I'm perfectly happy defining this utility method myself, but just wondered if it already exists somewhere.
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.
An Option[T] can be either Some[T] or None object, which represents a missing value. For instance, the get method of Scala's Map produces Some(value) if a value corresponding to a given key has been found, or None if the given key is not defined in the Map.
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 reference types such as Objects, and Strings can be nulland the value types such as Int, Double, Long, etc, cannot be null, the null in Scala is analogous to the null in Java.
scala> Option(null)
res0: Option[Null] = None
scala> Option(1)
res1: Option[Int] = Some(1)
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