I have Java piece of code that returns java.lang.Integer
and it can be null
:
someClass.getMyInteger
But when I use it in Scala classes I'm getting this error:
Caused by: java.lang.NullPointerException at scala.Predef$.Integer2int(Predef.scala:357)
I.e. Scala implicitly tries to convert Java's Integer
to Scala's Int
(using implicit Integer2int
method), but since in this case Integer
is null
it fails with exception.
How to solve this problem?
I would wrap it in an Option:
val x = Option(someClass.getMyInteger).map {_.toInt}
E.g.,
scala> val oneInt: java.lang.Integer = 1
oneInt: Integer = 1
scala> val nullInt: java.lang.Integer = null
nullInt: Integer = null
scala> val oneOpt: Option[Int] = Option(oneInt).map {_.toInt}
oneOpt: Option[Int] = Some(1)
scala> val nullOpt: Option[Int] = Option(nullInt).map {_.toInt}
nullOpt: Option[Int] = 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