Open In App

Scala Map remove() method with example

Last Updated : 13 Aug, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

The remove() method is utilized to remove a key from the map and return its value only.

Method Definition: def remove(key: A): Option[B]

Return Type: It returns the value of the key present in the above method as argument.

Example #1:




// Scala program of remove()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating map
        val m1 = scala.collection.mutable.Map("geeks" -> 5
                                    "for" -> 3, "cs" -> 2)
          
        // Applying remove method
        val result = m1.remove("for")
          
        // Displays output
        println(result)
      
    }
}


Output:

Some(3)

We use mutable map here, as remove method is a member of mutable map.
Example #2:




// Scala program of remove()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating map
        val m1 = scala.collection.immutable.Map("geeks" -> 5
                                        "for" -> 3, "cs" -> 2)
          
        // Applying remove method
        val result = m1.remove("for")
          
        // Displays output
        println(result)
      
    }
}


Output:

prog.scala:16: error: value remove is not a member of scala.collection.immutable.Map[String, Int]
val result = m1.remove(“for”)
^
one error found

So, if we use immutable map then there is a compile time error.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads