while programming some Scala I realized the following:
Map[Int, Option[Int]]().updated(3, None).get(3)
instead of the expected
This seems very counterintuitive. Is this expected behavior or is this a bug.
I’m on Scala 2.13.8 by the way.
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
Options, but instead use the plain
flattenthe result at the end:
A similar thing will happen if you put
Options — there’s no automagic flattening:
scala> Option(None) val res0: Option[None.type] = Some(None) scala> .flatten val res1: Option[Nothing] = None