Convert Scala Option to Java Optional

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]

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.