eclipse 如何从 Java 调用 scala 的 Option 构造函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5287451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 15:57:59  来源:igfitidea点击:

How to call scala's Option constructors from Java

javaeclipsescalaoption

提问by pkaeding

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:

我正在处理一个混合的 java/scala 项目,我试图从 Java 调用一个 scala 对象的方法。此方法将 anOption[Double]作为参数。我认为这会奏效:

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

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

但是 Eclipse 告诉我“构造函数 Some(Double) 未定义”。

Should I be calling the constructor for scala.Somedifferently?

我应该以scala.Some不同的方式调用构造函数吗?

回答by Vasil Remeniuk

In Scala you normally lift to Option as follows:

在 Scala 中,您通常按如下方式提升到 Option:

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:

()apply[A](A obj)方法Option的伴随对象的语法糖。因此,在Java中可以直接调用:

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

回答by sbridges

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

你可以这样构造一个 Some 实例,这对我来说编译,

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

The problem may be the missing generics, try doing,

问题可能是缺少泛型,尝试做,

scalaObj.scalaMethod(new Some<Double>(doubleValue));