Goldengirl Goldengirl - 24 days ago 6
Java Question

How to convert a scala Int to a java Integer?

I am reasonable new to scala and working with scala and Java together.

I am trying to pass a scala Int into a method that accepts an Integer(java.long.Integer). Since they are of different types the compiler gives an error.

/* name- Option[String], id- Option[Integer] , mask- Option[String]*/
new findingFrame(name,id, mask)

case class findingFrame(name: String,
id: Option[java.lang.Integer],
mask : Option[String])


I tried using .instanceOf [java.lang.Integer], but this doesn't work either..

I am not sure how to solve this.. Can somebody help me please?
Thank you.

Answer

Scala using box for primitive types, it can pass directly to Java.

In the following code, type i is actually int, and int can passed to Random which requires long since int will convert to long automatically.

val i = 3
println(i.getClass)
println(new Random(i))

Int the following code, using Option[Integer], Option[Integer].get will get the value inside which is type Integer. And Integer can not passed directly to long, while we can use .toLong to convert it to Long which will automatically unbox to long.

val oi: Option[Integer] = new Some(3)
println(oi.getClass)

println(new Random(oi.get.toLong))