Scala Map remove() method with example
Last Updated :
13 Aug, 2019
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:
object GfG
{
def main(args : Array[String])
{
val m 1 = scala.collection.mutable.Map( "geeks" - > 5 ,
"for" - > 3 , "cs" - > 2 )
val result = m 1 .remove( "for" )
println(result)
}
}
|
We use mutable map here, as remove method is a member of mutable map.
Example #2:
object GfG
{
def main(args : Array[String])
{
val m 1 = scala.collection.immutable.Map( "geeks" - > 5 ,
"for" - > 3 , "cs" - > 2 )
val result = m 1 .remove( "for" )
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.
Share your thoughts in the comments
Please Login to comment...