Convert Scala Option to Java Optional

我们两清 提交于 2019-12-21 04:00:13

问题


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();
}

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:

Options.asJava(option);

回答1:


The shortest way I can think of in Java is:

Optional.ofNullable(option.getOrElse(null))

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

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.




回答2:


There is an asJava solution now! It's available from 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.




回答3:


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

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

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




回答4:


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

From Java (the explicit way):

import scala.jdk.javaapi.OptionConverters;

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

From Scala (the implicit way):

import scala.jdk.OptionConverters._

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



回答5:


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)

}



回答6:


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

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




回答7:


Another nice lib:

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

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


来源:https://stackoverflow.com/questions/38325656/convert-scala-option-to-java-optional

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!