Scala Map clear() 方法与示例
clear()方法用于清除地图。 value clear 是 scala.collection.mutable.Map[String, Int] 的成员。
Method Definition: def clear(): Unit
Return Type: It returns empty map.
示例 #1:
// Scala program of clear()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a mutable map
val m1 = scala.collection.mutable.Map("geeks" -> 5,
"for" -> 3, "geeks" -> 1)
// Applying clear method
val result = m1.clear()
// Displays output
println(result)
}
}
输出:
()
这里使用了一个可变映射,因为 clear() 是 scala.collection.mutable.Map[String, Int] 的成员。
示例 #2:
// Scala program of clear()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a immutable map
val m1 = scala.collection.immutable.Map("geeks" -> 5,
"for" -> 3, "geeks" -> 1)
// Applying clear method
val result = m1.clear()
// Displays output
println(result)
}
}
输出:
prog.scala:16: error: value clear is not a member of scala.collection.immutable.Map[String, Int]
val result = m1.clear()
^
one error found
在这里,发现一个错误,因为使用了不可变映射,但clear方法是 scala.collection.mutable.Map[String, Int] 的成员。