Convert Scala Option to Java Optional

mjjaniec picture mjjaniec · Jul 12, 2016 · Viewed 19k times · Source

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

Answer

Xavier Guihot picture Xavier Guihot · Mar 29, 2019

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]