当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Scala Map remove()用法及代码示例


remove()方法用于从映射中删除键并仅返回其值。

函数定义: def remove(key: A): Option[B]

返回类型: 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

因此,如果我们使用不可变映射,则将出现编译时错误。



相关用法


注:本文由纯净天空筛选整理自nidhi1352singh大神的英文原创作品 Scala Map remove() method with example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。