Scala map isDefinedAt() 方法及示例
isDefinedAt()是PartialFunction trait的抽象值成员,它与contains方法相同,并在PartialFunction的所有类中观察到。它检查一个值是否包含在函数的定义域中。
- 方法定义:
abstract def isDefinedAt(x: A): Boolean
其中,x是要测试的值。
- 返回类型:
如果x存在于此函数的域中,则返回true,否则返回false。
示例:
// Scala program of isDefinedAt()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating partial function
val par : PartialFunction[Int,Int] =
{
case 1 => 1
}
// Applying isDefinedAt() method
val result = par.isDefinedAt(1)
// Displays output
println(result)
}
}
true
在这里,上面定义的值x存在于函数域中,因此返回true。
示例:
// Scala program of isDefinedAt()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a map
val map: Map[Int,Int] = Map(2 -> 3)
// Applying isDefinedAt() method
val result = map.isDefinedAt(5)
// Displays output
println(result)
}
}
false
在这里,上面定义的值x不存在于函数域中,因此返回false。
阅读更多:Scala 教程
极客教程