Convert Scala Option to Java Optional

前端 未结 7 1234
孤街浪徒
孤街浪徒 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 16:00

    Starting Scala 2.13, there is a dedicated converter from scala's Option to java's Optional.

    From Java (the explicit way):

    import scala.jdk.javaapi.OptionConverters;
    
    // val option: Option[Int] = Some(42)
    OptionConverters.toJava(option);
    // java.util.Optional[Int] = Optional[42]
    

    From Scala (the implicit way):

    import scala.jdk.OptionConverters._
    
    // val option: Option[Int] = Some(42)
    option.toJava
    // java.util.Optional[Int] = Optional[42]
    

提交回复
热议问题