while programming some Scala I realized the following:
Map[Int, Option[Int]]().updated(3, None).get(3)
returns
Some(None)
instead of the expected
None
This seems very counterintuitive. Is this expected behavior or is this a bug.
I’m on Scala 2.13.8 by the way.
>Solution :
It’s very much expected behavior. Option
is a "data structure" like any other, so there’s no special handling of it from the compiler’s side. If you associate a None
with a key in that map, then there’s an entry there and Map
will report it.
If you want the behavior you expected, then either:
- Don’t store values as
Option
s, but instead use the plainInt
type, or flatten
the result at the end:get(3).flatten
.
A similar thing will happen if you put Option
s inside Option
s — there’s no automagic flattening:
scala> Option(None)
val res0: Option[None.type] = Some(None)
scala> .flatten
val res1: Option[Nothing] = None