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.
val map = Map("eins" -> "one", "zwei" -> "two", "drei" -> "three").withDefault(identity)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With