Convert Scala Option to Java Optional

前端 未结 7 1251
孤街浪徒
孤街浪徒 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:48

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

提交回复
热议问题