Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Scala have a library method to wrap nullable return values in an Option?

Tags:

scala

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.

like image 542
Aaron Novstrup Avatar asked Jan 20 '10 23:01

Aaron Novstrup


People also ask

Can options be null Scala?

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.

How do I use options in Scala?

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.

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.

Can int be null in Scala?

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.


1 Answers

scala> Option(null)
res0: Option[Null] = None

scala> Option(1)
res1: Option[Int] = Some(1)
like image 121
Alexey Avatar answered Sep 25 '22 18:09

Alexey