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

前端 未结 3 655
囚心锁ツ
囚心锁ツ 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-17 14:57

    You are mixing Int and java.lang.Integer so

    val i: java.lang.Integer = null
    val o: Option[Int] = Option(i)
    

    implicitly converts to

    val o: Option[Int] = Option(Integer2int(i))
    

    which becomes

    val o: Option[Int] = Option(null.asInstanceOf[Int])
    

    thus

    val o: Option[Int] = Some(0)
    

    If you want to work with java.lang.Integer, then write

    val o: Option[java.lang.Integer] = Option(i)
    // o: Option[Integer] = None
    

提交回复
热议问题