日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Scala教程之:PartialFunction

發布時間:2024/2/28 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Scala教程之:PartialFunction 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Scala中有一個很有用的traits叫PartialFunction,我看了下別人的翻譯叫做偏函數,但是我覺得部分函數更加確切。

那么PartialFunction是做什么用的呢?簡單點說PartialFunction用在模式匹配中,是一個不完整的函數,它只實現了函數的部分功能,也就是列舉了部分case的情況。

我們先看下PartialFunction的定義:

trait PartialFunction[-A, +B] extends (A => B) { ...def isDefinedAt(x: A): Boolean...

我們可以看到PartialFunction是一個trait,它繼承自函數 (A => B), 這個函數有一個參數和一個返回值,在Scala中,該函數會被自動解析為Function1。

我們看下Function1的定義:

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

我們可以看到Function1定義了一個方法: def apply(v1: T1): R

PartialFunction也定義了一個方法: def isDefinedAt(x: A): Boolean

如果我們要自己實現一個PartialFunction,則必須實現上述兩個方法:

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

其中isDefinedAt用來選擇PartialFunction入參的范圍,而apply是真正的業務邏輯。

除了用new來實例化一個PartialFunction外,還有一個最簡單的方法就是使用case語句。 我們舉個例子, 如果我們有段case邏輯是匹配各個好吃等級,如下:

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")

我們使用了3個case語句,看起來比較繁瑣,使用PartialFunction, 我們可以將其轉換為如下的形式:

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

PartialFunction可以通過使用orElse關鍵字來合并成一個完整的Function。

我們看下這幾個PartialFunction該怎么定義:

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"}

實際上就是把整個的業務邏輯,用PartialFunction拆分開來了。這里使用case語句,會自動轉換成為PartialFunction。

關注下最后一個unknownTaste的case語句, @ 使用來做模式匹配的, case donut1 @ _ 就意味著 donut1 將會匹配所有的輸入。

更多精彩內容且看:

  • 區塊鏈從入門到放棄系列教程-涵蓋密碼學,超級賬本,以太坊,Libra,比特幣等持續更新
  • Spring Boot 2.X系列教程:七天從無到有掌握Spring Boot-持續更新
  • Spring 5.X系列教程:滿足你對Spring5的一切想象-持續更新
  • java程序員從小工到專家成神之路(2020版)-持續更新中,附詳細文章教程

更多教程請參考 flydean的博客

總結

以上是生活随笔為你收集整理的Scala教程之:PartialFunction的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。