# Scala教程之:PartialFunction

04/11 20:53

Scala中有一个很有用的traits叫PartialFunction，我看了下别人的翻译叫做偏函数，但是我觉得部分函数更加确切。

``````trait PartialFunction[-A, +B] extends (A => B) {
...

def isDefinedAt(x: A): Boolean

...``````

``````trait Function1[@specialized(scala.Int, scala.Long, scala.Float, scala.Double) -T1, @specialized(scala.Unit, scala.Boolean, scala.Int, scala.Float, scala.Long, scala.Double) +R] extends AnyRef { self =>
/** Apply the body of this function to the argument.
*  @return   the result of function application.
*/
def apply(v1: T1): R``````

PartialFunction也定义了一个方法： def isDefinedAt(x: A): Boolean

``````val inc = new PartialFunction[Any, Int] {
override def isDefinedAt(x: Any): Boolean = ???

override def apply(v1: Any): Int = ???
}``````

``````println("Step 1: Review of Pattern Matching in Scala")
val donut = "Glazed Donut"
val tasteLevel = donut match {
case "Glazed Donut" | "Strawberry Donut" => "Very tasty"
case "Plain Donut" => "Tasty"
case _  => "Tasty"
}
println(s"Taste level of \$donut = \$tasteLevel")``````

``````val donutTaste = isVeryTasty orElse isTasty orElse unknownTaste
println(donutTaste("Glazed Donut"))
println(donutTaste("Plain Donut"))
println(donutTaste("Chocolate Donut"))``````

PartialFunction可以通过使用orElse关键字来合并成一个完整的Function。

``````val isVeryTasty: PartialFunction[String, String] = {
case "Glazed Donut" | "Strawberry Donut" => "Very Tasty"
}

val isTasty: PartialFunction[String, String] = {
case "Plain Donut" => "Tasty"
}

val unknownTaste: PartialFunction[String, String] = {
case donut1 @ _ => s"Unknown taste for donut = \$donut1"
}``````

0
0 收藏

0 评论
0 收藏
0