Start learning free

LESSON 133 OF 291 · DICTIONARIES - CHALLENGES

Safe Lookup in Scala: getOrElse on a mutable.Map

Practice Read the full explanation

Given a mutable.Map scores from names to scores and a name, return the score of name, or 0 when name isn't a key of scores.

Some names you look up aren't in the dictionary at all. They have no score, so the answer for them is 0.

 

Example 1:

Input: scores = {"Ana": 90, "Ben": 75, "Cara": 88}, name = "Ben"
Output: 75
Explanation: "Ben" is a key of scores, and its value is 75.

Example 2:

Input: scores = {"Ana": 90, "Ben": 75, "Cara": 88}, name = "Dan"
Output: 0
Explanation: "Dan" isn't a key of scores, so the answer is 0.

Example 3:

Input: scores = {}, name = "Ana"
Output: 0
Explanation: An empty dictionary has no keys at all.

 

Constraints:

  • scores can be empty.
  • Names are single words made of English letters, and the names in scores are all different.
  • name matches a key only when it is spelled exactly the same, upper and lower case included: "ana" is not "Ana".
  • Every score is between 0 and 100.
STEP 1 OF 1
    Ctrl + Enter to check

    SCALA · DICTIONARIES - CHALLENGES

    Safe Lookup in Scala, explained

    Problem overview

    The method safeLookup gets scores, a scala.collection.mutable.Map[String, Int] from names to scores, and a name. It returns the score of that name, or 0 when the name isn't a key.

    With {"Ana": 90, "Ben": 75, "Cara": 88}, the name "Ben" gives 75 and the name "Dan" gives 0. An empty map gives 0 for every name.

    Approach

    The direct lookup scores(name) throws a NoSuchElementException when the key is missing. For a missing name the program would crash instead of answering 0. You could check scores.contains(name) first and branch, but getOrElse does both jobs in one call.

    Step by step

    There is one step: return scores.getOrElse(name, 0). The call returns the value stored under name when the key exists, and the default, 0, when it doesn't.

    The solution in Scala

    class Solution {
        def safeLookup(scores: scala.collection.mutable.Map[String, Int], name: String): Int = {
            return scores.getOrElse(name, 0)
        }
    }
    

    Language details:

    • getOrElse(key, default) takes the default as a by-name parameter, so it is only computed when the key is missing. A plain 0 costs nothing either way.
    • Scala has a third way to read a map: get(key) returns an Option, which is Some(value) or None. getOrElse on the map is the same as scores.get(name).getOrElse(0) in one step.
    • The result type is Int, matching the map's value type and the default.

    Edge cases and common mistakes

    • Using scores(name). It works for "Ben" but throws NoSuchElementException: key not found: Dan for "Dan".
    • Letter case. Keys are compared exactly. With the map above, "ana" is not a key, so the answer is 0 even though "Ana" has 90.
    • A stored 0. A name whose score is really 0 also gives 0. The answer is the same as for a missing name, which is what this task asks for.
    • The map isn't changed. getOrElse only reads. It doesn't add the missing key.

    Why a default helps

    A default value keeps the rest of a program simple. With getOrElse(name, 0), the result is always an Int, so it can go straight into arithmetic. Adding up the scores of the names "Ana", "Dan" and "Ben" from a map holding only Ana's 90 gives 90: the unknown names count as 0 and nothing crashes. Without a default, every caller would need its own check for missing names.

    Reading the lesson's examples

    In the first example, "Ben" is a key, so getOrElse returns his stored 75 and ignores the default. In the second, "Dan" isn't a key, so the default 0 comes back. The third example has an empty map, which has no keys at all, so every name takes the default. One call covers all three cases without any if.

    Other ways to write it

    Each of these gives the same answers as getOrElse:

    if (scores.contains(name)) scores(name) else 0
    
    scores.get(name) match {
      case Some(v) => v
      case None => 0
    }
    

    With {"Ana": 90}, the first returns 0 for "Dan" and the second returns 90 for "Ana". Both are longer, and the first looks the key up twice. getOrElse says "this value, or that default" in one call and is the usual choice.

    Remember that the method only answers the question. It never adds the missing name to scores, so the map is the same after the call as before it.

    Testing

    safeLookup({"Ana": 90, "Ben": 75, "Cara": 88}, "Ben")  -> 75
    safeLookup({"Ana": 90, "Ben": 75, "Cara": 88}, "Dan")  -> 0
    safeLookup({"Ana": 90, "Ben": 75, "Cara": 88}, "ana")  -> 0
    safeLookup({}, "Ana")                                   -> 0
    
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free