Search code examples
scala

What is a proper way of checking if a Scala Map key doesn't exist?


I'm new to scala and I'm trying to figure out how to not error out if Map key is not found. I have a map as such:

val dict_a = Map("apple" -> "198.0.0.1")

I want to see if be able to able to check and assign the value for key or else assign null something as such. New to scala so not sure how it's done.

I want to do something like this....

val inp = "apple"
val link = if (dict_a(inp)) dict_a(inp) else null

Solution

  • Here is some example usages for checking if a key exists or not:

    scala> val myMap = Map[String, Int]("hello" -> 34)
    myMap: scala.collection.immutable.Map[String,Int] = Map(hello -> 34)
    
    // lookup the key hello. Returns an Option which can denote a 
    // a value being present or not.. instead of using null.    
    
    scala> myMap.get("hello")
    res1: Option[Int] = Some(34)
    
    scala> myMap.get("hello").isDefined
    res2: Boolean = true
    
    // if key is not in map.. return this default value
    // similar to your example    
    
    scala> myMap.getOrElse("hello", 0)
    res3: Int = 34
    
    scala> myMap.getOrElse("not-exist", 0)
    res4: Int = 0
    
    scala> myMap.updated("not-exist", 33)
    res5: scala.collection.immutable.Map[String,Int] = Map(hello -> 34, not-exist -> 33)
    
    // this .exists function allow you to inspect the key and the
    // value, or both or neither...
    
    scala> myMap.exists { case (k, v) => k == "hello" && v == 34 }
    res10: Boolean = true
    
    scala> myMap.exists { case (k, v) => k == "hello" }
    res11: Boolean = true
    
    scala> myMap.filterKeys(_ == "hello")
    res13: scala.collection.immutable.Map[String,Int] = Map(hello -> 34)