25

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?

dbc
  • 104,963
  • 20
  • 228
  • 340
pkaeding
  • 36,513
  • 30
  • 103
  • 141
  • 1
    In Java, type parameters for _methods_ can be inferred (sometimes), but type parameters for _constructors_ never. – Alexey Romanov Mar 13 '11 at 05:55
  • @Alexey good to know, I think that is probably the source of my troubles. I am still having problems, even if I parameterize `Some`, though (see my comment on the answer from @user654801). – pkaeding Mar 13 '11 at 05:57

2 Answers2

51

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);
Vasil Remeniuk
  • 20,519
  • 6
  • 71
  • 81
  • This helped me as well. Scala `def startServer(localBind: Option[Int] = None): Unit = { ... }` Java call `Option so = Option.apply(9002);` `AcmeClient.startServer(so);` – drusolis Aug 19 '16 at 15:39
1

You can construct a Some instance that way, this compiles for me,

Some<Double> d = new Some<Double>(Double.valueOf(1));

The problem may be the missing generics, try doing,

scalaObj.scalaMethod(new Some<Double>(doubleValue));
sbridges
  • 24,960
  • 4
  • 64
  • 71
  • Hmm, when I try that I get "The type Some is not generic; it cannot be parameterized with arguments ". Could this just be a deficiency in the Eclipse/Scala integration? I do have `import scala.Some;` so I believe I am using the right `Some`. – pkaeding Mar 13 '11 at 05:54
  • 6
    This approach has the downside of lifting `null` reference to `Some(null)`, instead of `None`. You'd better use `Option` companion object for correct lifting. – Vasil Remeniuk Mar 13 '11 at 06:50
  • @Vasil, thanks, that makes sense. Your (other) answer solved my problem. – pkaeding Mar 13 '11 at 06:56