Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: How to get back the key itself when a Map does not contain it

Tags:

scala

Let's assume the following Map:

val map = Map("eins" -> "one", "zwei" -> "two", "drei" -> "three")

As expected map returns the value associated with a given key:

scala> map("eins")
res0: String = one
scala> map("zwei")
res1: String = two
...

and of course it crashes if a given key does not exist:

scala> map("zehn")
java.util.NoSuchElementException: key not found: zehn

Is there a way to get back the key itself instead of an exception?

map("zehn") -> "zehn"

Thanks.

like image 331
j3d Avatar asked Dec 21 '25 14:12

j3d


1 Answers

val map = Map("eins" -> "one", "zwei" -> "two", "drei" -> "three").withDefault(identity)
like image 64
ghik Avatar answered Dec 24 '25 07:12

ghik