Map[Int, Option[Int]] returns Some(None)

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:

  1. Don’t store values as Options, but instead use the plain Int type, or
  2. flatten the result at the end: get(3).flatten.

A similar thing will happen if you put Options inside Options — there’s no automagic flattening:

scala> Option(None)
val res0: Option[None.type] = Some(None)

scala> .flatten
val res1: Option[Nothing] = None

Leave a Reply