How to call scala's Option constructors from Java

杀马特。学长 韩版系。学妹 提交于 2019-12-09 14:09:26

问题


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?


回答1:


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);



回答2:


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));


来源:https://stackoverflow.com/questions/5287451/how-to-call-scalas-option-constructors-from-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!