Scala 函数式编程_偏函数_Partial Functions
Scala 函数式编程_偏函数_Partial Functions

Scala 函数式编程_偏函数_Partial Functions
• 发表于 3年前
• 阅读 53
• 收藏 0
• 评论 0

Scala 函数式编程_偏函数_Partial Functions

# 偏函数_Partial Functions

``````val one: PartialFunction[Int, String] = {
case 1 => "one"
case 2 => "two"
}

println(one.isDefinedAt(1))

println(one.isDefinedAt(2))

println(one(1))
println(one(2))``````

true

true

one

two

isDefinedAt表示 这个参数是否在函数的定义域中，否则抛出异常。

...........

...........

false

scala.MatchError: 3 (of class java.lang.Integer)

at scala.PartialFunction\$\$anon\$1.apply(PartialFunction.scala:253)

at scala.PartialFunction\$\$anon\$1.apply(PartialFunction.scala:251)

``````val signal: PartialFunction[Int, Int] = {
case x if x > 1 => 1
case x if x < -1 => -1
}

println(signal(1212))
println(signal(-74567))
println(signal(0))``````

C:\WorkSpace6-scala\scala-train\src\com\usoft>scala PartialFunction.scala

1

-1

scala.MatchError: 0 (of class java.lang.Integer)

at scala.PartialFunction\$\$anon\$1.apply(PartialFunction.scala:253)

# 使用 orElse 组合函数

``````val one: PartialFunction[Int, String] = {
case 1 => "one"
}
val two: PartialFunction[Int, String] = {
case 2 => "two"
}
val three: PartialFunction[Int, String] = {
case 3 => "three"
}
val wildcard: PartialFunction[Int, String] = {
case _ => "something else"
}

val partial = one orElse two orElse three orElse wildcard

println(partial.isDefinedAt(4))
println(partial(4))``````

C:\WorkSpace6-scala\scala-train\src\com\usoft>scala PartialFunction.scala

true

something else

=============END=============

×