开发者

How to call scala's Option constructors from Java

开发者 https://www.devze.com 2023-02-16 17:16 出处:网络
I am working on a mixed java/scala pr开发者_开发知识库oject, 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:

I am working on a mixed java/scala pr开发者_开发知识库oject, 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?


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号