从 Java 访问 scala.None
如何从 Java 访问 scala.None?
最后一行导致编译器因“type scala.None does not take parameters”而终止。
import scala.Option;
import scala.Some;
import scala.None;
final Option<String> object1 = new Some<String>("Hi there");
final Option<String> object2 = new None<String>();
这会失败,并显示“无法找到符号构造函数 None()”:
final Option<String> object2 = new None();
这会失败,并显示“无法找到符号变量 None”:
final Option<String> object2 = None;
在 2007 年,这曾经可以工作,但后来 Scala 发生了变化。 Java 编译器给出错误:不兼容的类型
:
final Option<String> object2 = scala.None$.MODULE$;
How can you access scala.None
from Java?
The last line causes the compiler to die with "type scala.None does not take parameters".
import scala.Option;
import scala.Some;
import scala.None;
final Option<String> object1 = new Some<String>("Hi there");
final Option<String> object2 = new None<String>();
This fails with "cannot find symbol constructor None()":
final Option<String> object2 = new None();
This fails with "cannot find symbol variable None":
final Option<String> object2 = None;
In 2007 this used to work, but then Scala changed. The Java compiler gives error: incompatible types
:
final Option<String> object2 = scala.None$.MODULE$;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这可能有效:
This might work:
使用 Scala 2.10.2(不确定是什么版本出现的):
Using Scala 2.10.2 (not sure at what version when this came in):
不要过分强调这一点,但不应依赖静态转发器,因为它们在某些情况下可能不会生成。例如,
Some
没有为其对象同伴提供静态转发器。当前访问对象伴生方法的方法是这样的:
Option$
是Option
对象伴生的类。MODULE$
是一个最终的公共静态字段,其中包含Option$
的唯一实例(换句话说,对象同伴)。Not to put too fine a point on it, but one shouldn't rely on static forwarders, as they might not get generated under certain circumstances. For instance,
Some
doesn't have static forwarders for its object companion.The current way of accessing methods on an object companion is this:
Option$
is the class for the object companion ofOption
.MODULE$
is a final public static field that contains the sole instance ofOption$
(in other words, the object companion).您可以导入
然后:
You can import
And then:
您可以执行以下操作(我对其进行了测试,它在 Scala 2.9.1 和 Java 1.6 上运行良好):
You can do the following (I tested it out and it works fine for me with Scala 2.9.1 and Java 1.6):
使用 Scala 版本 2.11.4,在我的例子中唯一有效的是
Update: a day after...
没有类型参数也可以工作,因为它应该。由于某种原因,我第一次尝试时无法让 Intellij 编译代码。我必须传递辅助类型参数。现在它可以编译了,只是不要问
Using Scala version 2.11.4 the only thing that worked out in my case, was
Update: a day later...
without the type parameter does work too, as it should. For some reason I couldn't get Intellij to compile the code on my first attempt. I had to pass the secondary type parameter. Now it compiles, just don't ask