Convert Scala Option to Java Optional

前端 未结 7 1420
孤街浪徒
孤街浪徒 2021-02-12 15:39

I need to convert Scala Option to Java Optional. I managed to wrote this:

public  Optional convertOption2Optional(Option option) {
           


        
7条回答
  •  野的像风
    2021-02-12 15:50

    The shortest way I can think of in Java is:

    Optional.ofNullable(option.getOrElse(null))
    

    @RégisJean-Gilles actually suggested even shorter if you are writing the conversion in Scala:

    Optional.ofNullable(option.orNull)
    

    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.

提交回复
热议问题