Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading