Convert Scala Option to Java Optional

2020-06-10 15:37发布

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

7条回答
何必那么认真
2楼-- · 2020-06-10 16:32

For a given input parameter opt: Option[T] of some class, you can define a method inside that class like the following:

def toOptional(implicit ev: Null <:< T): Optional[T] = Optional.ofNullable(opt.orNull).

查看更多
登录 后发表回答