scala/Int, scala/Float <-> java.lang.Object

I am dealing with a Java API that takes [java.lang.Object] as input and produces a java.lang.Object as output.

How do I do conversions of ?

  scala/Int => java.lang.Object
  scala/Float => java.lang.Object
  java.lang.Object => maybe scala/Int
  java.lang.Object => maybe scala/Float

I have tried googling this, but instead of getting conversion / casting info, all the links so far have been about the ‘object’ keyword in Scala.

One way is to cast, wrapped in Try and mapped by .toOption in the case of optional conversions.

@ val one = 1.asInstanceOf[java.lang.Object] 
one: Object = 1

@ import scala.util.Try 
import scala.util.Try

@ Try(one.asInstanceOf[Int]) 
res2: Try[Int] = Success(1)

@ Try(one.asInstanceOf[Int]).toOption 
res3: Option[Int] = Some(1)

@ Try(one.asInstanceOf[String]).toOption 
res4: Option[String] = None