learning scala PartialFunction
Posted lianghong881018
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了learning scala PartialFunction相关的知识,希望对你有一定的参考价值。
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
以上是关于learning scala PartialFunction的主要内容,如果未能解决你的问题,请参考以下文章
learning scala control statement
learning scala for comprehensions
learning scala pattern matching 03