将 Scala Option 转换为 Java Optional

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38325656/
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-10-22 08:28:39  来源:igfitidea点击:

Convert Scala Option to Java Optional

javascalascala-java-interop

提问by mjjaniec

I need to convert Scala Option to Java Optional. I managed to wrote this:

我需要将 Scala Option 转换为 Java Optional。我设法写了这个:

public <T> Optional<T> convertOption2Optional(Option<T> option) {
    return option.isDefined() ? Optional.of(option.get()) : Optional.empty();
}

But I don't like it.

但我不喜欢。

Is there a simple way to do it, or a built-in scala converter? I'm looking for something like:

有没有简单的方法来做到这一点,或者有一个内置的 Scala 转换器?我正在寻找类似的东西:

Options.asJava(option);

采纳答案by Dici

The shortest way I can think of in Java is:

我在 Java 中能想到的最短方法是:

Optional.ofNullable(option.getOrElse(null))

@RégisJean-Gilles actually suggested even shorter if you are writing the conversion in Scala:

如果您在 Scala 中编写转换,@RégisJean-Gilles 实际上建议更短:

Optional.ofNullable(option.orNull)

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 直到 Scala 2.12 才支持 Java 8,该版本尚未正式发布。查看文档(在发布之前可能会更改)在JavaConversions.

回答by Xavier Guihot

Starting Scala 2.13, there is a dedicated converter from scala's Optionto java's Optional.

首先Scala 2.13,有一个从 scalaOption到 java 的专用转换器Optional

From Java(the explicitway):

从 Java显式方式):

import scala.jdk.javaapi.OptionConverters;

// val option: Option[Int] = Some(42)
OptionConverters.toJava(option);
// java.util.Optional[Int] = Optional[42]

From Scala(the implicitway):

从 Scala隐式方式):

import scala.jdk.OptionConverters._

// val option: Option[Int] = Some(42)
option.toJava
// java.util.Optional[Int] = Optional[42]

回答by Java Xu

There is an asJavasolution now! It's available from 2.10.

asJava现在有解决方案!它可以从2.10.

Example:

例子:

import scala.compat.java8.OptionConverters._

class Test {
  val o = Option(2.7)
  val oj = o.asJava        // Optional[Double]
  val ojd = o.asPrimitive  // OptionalDouble
  val ojds = ojd.asScala   // Option(2.7) again
}

More details here.

更多细节在这里

回答by Michal M

You can also use some of the abundant utilities out there on the github, e.g.:

您还可以使用 github 上的一些丰富的实用程序,例如:

https://gist.github.com/julienroubieu/fbb7e1467ab44203a09f

https://gist.github.com/julienroubieu/fbb7e1467ab44203a09f

https://github.com/scala/scala-java8-compat

https://github.com/scala/scala-java8-compat

回答by Zhuo YING

I am doing this:

我正在这样做:

import java.util.{Optional => JOption}

package object myscala {

    implicit final class RichJOption[T](val optional: JOption[T]) {

        def asScala: Option[T] = optional match {
            case null => null
            case _ => if (optional.isPresent) Option(optional.get()) else None
        }

    }

    implicit final class RichOption[T](val option: Option[T]) {

        def asJava: JOption[T] = option match {
            case null => null
            case _ => if (option.isDefined) JOption.of(option.get) else JOption.empty()
        }

    }
}

so, you can use it like this, :)

所以,你可以这样使用它,:)

import myscala._

object Main extends App {

    val scalaOption = java.util.Optional.ofNullable("test").asScala
    println(scalaOption)

    val javaOption = Option("test").asJava
    println(javaOption)

}

回答by Hari Bage

For a given input parameter opt: Option[T]of some class, you can define a method inside that class like the following:

对于opt: Option[T]某个类的给定输入参数,您可以在该类中定义一个方法,如下所示:

def toOptional(implicit ev: Null <:< T): Optional[T] = Optional.ofNullable(opt.orNull).

def toOptional(implicit ev: Null <:< T): Optional[T] = Optional.ofNullable(opt.orNull).

回答by mjjaniec

Another nice lib:

另一个不错的库:

https://github.com/AVSystem/scala-commons

https://github.com/AVSystem/scala-commons

import com.avsystem.commons.jiop.JavaInterop._
Optional.of("anything").asScala