mjjaniec mjjaniec - 4 months ago 84
Java Question

Convert Scala Option to 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();
}


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

The shortest way I can think of is

Optional.ofNullable(option.getOrElse(null))

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.