val i: java.lang.Integer = null
val o: Option[Int] = Option(i) // This yields Some(0)
What is the safe way to convert null: java.lang.Integer
to Scala Option[Int]
?
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.
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. AnyRef. We must try to avoid using null while initializing variables if there's an empty value of the variable's type available, such as Nil.
We can test whether an Option is Some or None using these following methods: isDefined – true if the object is Some. nonEmpty – true if the object is Some. isEmpty – true if the object is None.
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. Null: It is a Trait, which is a subset of each of the reference types but is not at all a sub-type of value types and a single instance of Null is null.
If the element does not exist, it is an instance of None The above is an example of an optional string value. Why Use Options? Options provide a more elegant way of handling absent values in Scala.
The Option class is used to represent optional values in Scala. By representing values as either an instance of Some or None, Scala provides a more elegant way of handling null values.
If the element does not exist, it is an instance of None The above is an example of an optional string value. Why Use Options? Options provide a more elegant way of handling absent values in Scala. While traditional Java uses null to represent empty or missing values, this can lead to NullPointerException that break your code at runtime.
You are mixing Int
and java.lang.Integer
so
val i: java.lang.Integer = null
val o: Option[Int] = Option(i)
implicitly converts to
val o: Option[Int] = Option(Integer2int(i))
which becomes
val o: Option[Int] = Option(null.asInstanceOf[Int])
thus
val o: Option[Int] = Some(0)
If you want to work with java.lang.Integer
, then write
val o: Option[java.lang.Integer] = Option(i)
// o: Option[Integer] = None
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