Scala的contains()方法等效於Scala的isDefinedAt方法,但唯一的區別是,在所有PartialFunction類上都可以看到isDefinedAt,而contains明確定義為Scala的Map接口。它檢查指定的映射是否包含鍵的綁定。
-
方法定義:
def contains(key: K): Boolean
其中,k是關鍵。
-
返回類型:
如果映射中所述鍵存在綁定,則返回true,否則返回false。
例:
// Scala program of contains()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a map
val map: Map[Int,Int] = Map(2 -> 3)
// Applying contains method
val result = map.contains(2)
// Displays output
println(result)
}
}
輸出:
true
在這裏,contains方法具有與上述映射中存在的鍵相同的鍵,因此它返回true。
例:
// Scala program of contains()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a map
val map: Map[Int,Int] = Map(4 -> 7)
// Applying contains method
val result = map.contains(5)
// Displays output
println(result)
}
}
輸出:
false
在這裏,contains方法具有與上述映射中存在的鍵不同的鍵,因此它返回false。
相關用法
- Scala Map take()用法及代碼示例
- Scala Set take()用法及代碼示例
- Scala Set ++()用法及代碼示例
- Scala Set -()用法及代碼示例
- Scala Int self()用法及代碼示例
- Scala Int min()用法及代碼示例
- Scala Set +()用法及代碼示例
- Scala map()用法及代碼示例
- Scala Map get()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Scala map contains() method with example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。