I need to convert Scala Option to Java Optional. I managed to wrote this:
public Optional convertOption2Optional(Option option) {
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)
}