如何在 Java 代码中使用 scala.None
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1997433/
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
How to use scala.None from Java code
提问by Craig B.
Possible Duplicate:
Accessing scala.None from Java
可能的重复:
从 Java 访问 scala.None
In Java you can create an instance of Someusing the constructor, i.e. new Some(value), but Nonehas no partner class. How do you pass Noneto a Scala function from Java?
在 Java 中,您可以创建一个Some使用构造函数的实例,即new Some(value),但None没有伙伴类。如何None从 Java传递给 Scala 函数?
采纳答案by Mitch Blevins
I think this ugly bit will work: scala.None$.MODULE$
我认为这个丑陋的部分会起作用: scala.None$.MODULE$
There is no need for a new instance since one None is as good as another...
不需要一个新实例,因为一个 None 和另一个一样好......
回答by Seth Tisue
The scala.None$.MODULE$thing doesn't always typecheck, for example this doesn't compile:
该scala.None$.MODULE$事情并不总是进行类型检查,比如这并不编译:
scala.Option<String> x = scala.None$.MODULE$;
because javac doesn't know about Scala's declaration-site variance, so you get:
因为 javac 不知道 Scala 的声明站点差异,所以你得到:
J.java:3: incompatible types
found : scala.None$
required: scala.Option<java.lang.String>
scala.Option<String> x = scala.None$.MODULE$ ;
This does compile, though:
不过,这确实可以编译:
scala.Option<String> x = scala.Option.apply(null);
so that's a different way to get a None that is usable in more situations.
所以这是获得在更多情况下可用的 None 的不同方法。
回答by Randall Schulz
You can access the singleton None instance from java using:
您可以使用以下方法从 java 访问单例 None 实例:
scala.None$.MODULE$
回答by Yuvi Masory
I've found this this generic function to be the most robust. You need to supply the type parameter, but the cast only appears once, which is nice. Some of the other solutions will not work in various scenarios, as your Java compiler may inform you.
我发现这个通用函数是最健壮的。您需要提供类型参数,但强制转换只出现一次,这很好。其他一些解决方案在各种情况下都不起作用,因为您的 Java 编译器可能会通知您。
import scala.None$;
import scala.Option;
public class ScalaLang {
public static <T> Option<T> none() {
return (Option<T>) None$.MODULE$;
}
}
public class ExampleUsage {
static {
//for example, with java.lang.Long
ScalaLang.<Long>none();
}
}
回答by Alex Cruise
Faced with this stinkfest, my usual modus operandi is:
面对这个臭烘烘的节日,我通常的作案手法是:
Scala:
斯卡拉:
object SomeScalaObject {
def it = this
}
Java:
爪哇:
doStuff(SomeScalaObject.it());

