问题描述
我需要将Scala Option转换为Java Optional.我设法这样写:
I need to convert Scala Option to Java Optional. I managed to wrote this:
public <T> Optional<T> convertOption2Optional(Option<T> option) {
return option.isDefined() ? Optional.of(option.get()) : Optional.empty();
}
但我不喜欢它.
有没有简单的方法或内置的scala转换器?我正在寻找类似的东西:
Is there a simple way to do it, or a built-in scala converter?I'm looking for something like:
Options.asJava(option);
推荐答案
我在Java中想到的最短的方法是:
The shortest way I can think of in Java is:
Optional.ofNullable(option.getOrElse(null))
@RégisJean-Gilles实际上建议如果使用Scala编写转换,则建议使用更短的时间:
@RégisJean-Gilles actually suggested even shorter if you are writing the conversion in Scala:
Optional.ofNullable(option.orNull)
通过这种方式,您必须知道Scala在Scala 2.12之前尚不支持Java 8,Scala 2.12尚未正式发布.查看 docs (可能会有所变化,直到发布为止).JavaConversions
中没有此类转换.
By the way you must know that Scala does not support Java 8 until Scala 2.12, which is not officially out yet. Looking at the docs (which may change until the release) there is no such conversion in JavaConversions
.
这篇关于将Scala选项转换为Java可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!