Partial函数的定义
scala> val isveryTasty: PartialFunction[String, String] = { case "Glazed Donut" | "StrawBerry Donut" => "Very Tasty"}
isveryTasty: PartialFunction[String,String] = <function1>
scala> isveryTasty("Glazed Donut")
res3: String = Very Tasty
Partianl函数的组合使用:
code :
println("\nStep 1: How to define a Partial Function named isveryTasty") val isveryTasty: PartialFunction[String, String] = { case "Glazed Donut" | "StrawBerry Donut" => "Very Tasty"} println("\nStep 2: How to call the Partial Function named isveryTasty") println(s"Calling partial function isveryTasty = ${isveryTasty("Glazed Donut")}") // NOTE: you will get scala.MatchError println("\nStep 3: How to define PartialFunction named isTasty and unkNownTaste") val isTasty: PartialFunction[String, String] = { case "Plain Donut" => "Tasty" } val unkNownTaste: PartialFunction[String, String] = { case donut @ _ => s"UnkNown taste for donut = $donut" } println("\nStep 4: How to compose PartialFunction using orElse") val donutTaste = isveryTasty orElse isTasty orElse unkNownTaste println(donutTaste("Glazed Donut")) println(donutTaste("Plain Donut")) println(donutTaste("Chocolate Donut"))
result:
Step 1: How to define a Partial Function named isveryTasty Step 2: How to call the Partial Function named isveryTasty Calling partial function isveryTasty = Very Tasty Step 3: How to define PartialFunction named isTasty and unkNownTaste Step 4: How to compose PartialFunction using orElse Very Tasty Tasty UnkNown taste for donut = Chocolate Donut
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。