Scala Option(null) expected as None but I got Some(0)

前端 未结 3 654
囚心锁ツ
囚心锁ツ 2021-01-17 14:29
val i: java.lang.Integer = null
val o: Option[Int] = Option(i) // This yields Some(0)

What is the safe wa

3条回答
  •  花落未央
    2021-01-17 15:12

    This seems to be happening because you are creating the Option, and converting it to an Int in one step (@MarioGalic's answer explains why this is happening).

    This does what you want:

    scala> val o: java.lang.Integer = null
    o: Integer = null
    
    scala> val i: Option[Int] = Option(o).map(_.toInt)
    i: Option[Int] = None
    
    scala> val o1: java.lang.Integer = 1
    o1: Integer = 1
    
    scala> val i1: Option[Int] = Option(o1).map(_.toInt)
    i1: Option[Int] = Some(1)
    

提交回复
热议问题