Scala Map remove() 方法与示例
remove()方法用于从映射中删除键并仅返回其值。
Method Definition: def remove(key: A): Option[B]
Return Type: It returns the value of the key present in the above method as argument.
示例 #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)
}
}
输出:
Some(3)
我们在这里使用可变映射,因为remove方法是可变映射的成员。
示例 #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)
}
}
输出:
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
因此,如果我们使用不可变映射,则会出现编译时错误。