WelcomeTo
WelcomeTo

Reputation: 20571

Convert Java's Integer to Scala's Int

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?

Upvotes: 11

Views: 10135

Answers (1)

Jack Leow
Jack Leow

Reputation: 22477

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

Upvotes: 18

Related Questions