How to call scala's Option constructors from Java

pkaeding picture pkaeding · Mar 13, 2011 · Viewed 15.7k times · Source

I am working on a mixed java/scala project, and I am trying to call a scala object's method from Java. This method takes an Option[Double] as a parameter. I thought this would work:

Double doubleValue = new Double(1.0);
scalaObj.scalaMethod(new Some(doubleValue));

But Eclipse tells me "The constructor Some(Double) is undefined".

Should I be calling the constructor for scala.Some differently?

Answer

Vasil Remeniuk picture Vasil Remeniuk · Mar 13, 2011

In Scala you normally lift to Option as follows:

scala> val doubleValue = Option(1.0)
doubleValue: Option[Double] = Some(1.0)

() is a syntactic sugar for apply[A](A obj) method of Option's companion object. Therefore, it can be directly called in Java:

Option<Double> doubleValue = Option.apply(1.0);