码迷,mamicode.com
首页 > 其他好文 > 详细

learning scala PartialFunction

时间:2019-07-12 11:19:01      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:code   not   get   and   erro   ror   cal   func   note   

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

标签:code   not   get   and   erro   ror   cal   func   note   

原文地址:https://www.cnblogs.com/lianghong881018/p/11174823.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!