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

浪子不回头ぞ 提交于 2020-06-08 16:26:07

问题


val i: java.lang.Integer = null
val o: Option[Int] = Option(i) // This yields Some(0)

What is the safe way to convert null: java.lang.Integer to Scala Option[Int]?


回答1:


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



回答2:


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)



回答3:


Faced the same issue before. This questionable behavior is known by the Scala team. Seems that changing it breaks something elsewhere. See https://github.com/scala/bug/issues/11236 and https://github.com/scala/scala/pull/5176 .



来源:https://stackoverflow.com/questions/60600502/scala-optionnull-expected-as-none-but-i-got-some0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!