當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。