Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Java's Integer to Scala's Int

Tags:

java

scala

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?

like image 939
WelcomeTo Avatar asked Aug 12 '15 23:08

WelcomeTo


Video Answer


1 Answers

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
like image 103
Jack Leow Avatar answered Sep 25 '22 23:09

Jack Leow