Scala中的部分函数
Scala部分函数
部分函数是一个函数,只为一组特定的值返回值,即该功能不能用于某些输入值返回值。定义此函数的目的是在处理代码时仅允许某些值。像被0除的情况一样,我们需要限制除法以避免错误。
这些是Scala编程语言的不一致功能,在某些情况下,它们可能很有用。
Scala中部分函数的实现也需要其他方法。用于实现的方法是apply()和isDefinedAt()。另外,您使用case语句来实现它。
apply()方法用于显示功能的应用。
isDefinedAt()方法用于检查值是否在函数范围内。
语法:
var function_name = new PartialFunction[input_type, return_type]
范例1:
使用和方法实现部分功能。isdefinedat()apply()
object MyObject
{
val divide = new PartialFunction[Int, Int]
{
def isDefinedAt(q: Int) = q != 0
def apply(q: Int) = 124 / q
}
def main(args: Array[String])
{
println("该数字除以12是 " + divide(12))
}
}输出结果
该数字除以12是 10
范例2:
使用orElse语句实现部分函数。
object MyObject
{
val Case1: PartialFunction[Int, String] =
{
case x if (x % 3) != 0 => "Odd"
}
val Case2: PartialFunction[Int, String] =
{
case y if (y % 2) == 0 => "Even"
}
val evenorodd = Case1 orElse Case2
def main(args: Array[String])
{
var x= 324
println("number "+x+" is "+evenorodd(x))
}
}输出结果
number 324 is Even
范例3:
使用andThen语句实现部分函数。
object MyObject
{
def main(args: Array[String])
{
val operation1: PartialFunction[Int, Int] =
{
case x if (x%4)!= 0=> x*42
}
val operation2=(x: Int)=> x/3
val op = operation1 andThen operation2
println("Initial value is 34\t and the value after operations is "+op(34))
}
}输出结果
Initial value is 34 and the value after operations is 476
热门推荐
10 新年祝福语简短的感谢
11 商务感恩祝福语大全简短
12 成年礼简短的祝福语
13 姐妹生日祝福语女孩简短
14 孩子新年祝福语简短精辟
15 牛年的吉祥祝福语简短
16 文艺乔迁祝福语简短精辟
17 考进高中祝福语简短
18 媒人婚礼祝福语简短大气