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);
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
Starting
Scala 2.13
, there is a dedicated converter from scala'sOption
to java'sOptional
.From Java (the explicit way):
From Scala (the implicit way):
The shortest way I can think of in Java is:
@RégisJean-Gilles actually suggested even shorter if you are writing the conversion in Scala:
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
.There is an
asJava
solution now! It's available from2.10
.Example:
More details here.
I am doing this:
so, you can use it like this, :)
Another nice lib:
https://github.com/AVSystem/scala-commons