Scala Map remove() method with example
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 m 1 = scala.collection.mutable.Map( "Beginner" - > 5 , "for" - > 3 , "cs" - > 2 ) // Applying remove method val result = m 1 .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 m 1 = scala.collection.immutable.Map( "Beginner" - > 5 , "for" - > 3 , "cs" - > 2 ) // Applying remove method val result = m 1 .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.
Contact Us