Scala 隱式轉換及應用

什麼是隱式轉換

咱們常常引入第三方庫,但當咱們想要擴展新功能的時候一般是很不方便的,由於咱們不能直接修改其代碼。scala提供了隱式轉換機制和隱式參數幫咱們解決諸如這樣的問題。
Scala中的隱式轉換是一種很是強大的代碼查找機制。當函數、構造器調用缺乏參數或者某一實例調用了其餘類型的方法致使編譯不經過時,編譯器會嘗試搜索一些特定的區域,嘗試使編譯經過。編程

場景一,如今咱們要爲Java的File類提供一個得到全部行數的方法:設計模式

implicit class Files(file: File) { def lines: Array[String] = { val fileReader: FileReader = new FileReader(file) val reader = new BufferedReader(fileReader) try { var lines = Array[String]() var line = reader.readLine() while (line != null) { lines = lines :+ line line = reader.readLine() } lines } finally { fileReader.close() reader.close() } } } private val file: File = new File("/path/to") file.lines foreach println 

場景二,我指望能夠像操做集合那樣來操做一個文件中的全部行。好比,對全部的行映射(map)一個指定函數。ide

implicit def file2Array(file: File): Array[String] = file.lines def map[R](source: Array[String])(fn: String ⇒ R) = { source.map(fn) } map(new File("/path/to"))(println) 

隱式操做規則

  1. 標記規則:只有標記爲implicit的變量,函數或對象定義才能被編譯器當作隱式操做目標。函數

  2. 做用域規則:插入的隱式轉換必須是單一標示符的形式處於做用域中,或與源/目標類型關聯在一塊兒。單一標示符是說當隱式轉換做用時應該是這樣的形式:file2Array(arg).map(fn)的形式,而不是foo.file2Array(arg).map的形式。假設file2Array函數定義在foo對象中,咱們應該經過import foo._或者import foo.file2Array把隱式轉換導入。簡單來講,隱式代碼應該能夠被"直接"使用,不能再依賴類路徑。
    假如咱們把隱式轉換定義在源類型或者目標類型的伴生對象內,則咱們能夠跳過單一標示符的規則。由於編譯器在編譯期間會自動搜索源類型和目標類型的伴生對象,以嘗試找到合適的隱式轉換。ui

  3. 無歧義規則:不能存在多於一個隱式轉換使某段代碼編譯經過。由於這種狀況下會產生迷惑,編譯器不能肯定到底使用哪一個隱式轉換。spa

  4. 單一調用規則:不會疊加(重複嵌套)使用隱式轉換。一次隱式轉化調用成功以後,編譯器不會再去尋找其餘的隱式轉換。scala

  5. 顯示操做優先規則:當前代碼類型檢查沒有問題,編譯器不會嘗試查找隱式轉換。設計

隱式解析的搜索範圍

隱式轉換自己是一種代碼查找機制,因此下面會介紹隱式轉換的查找範圍:
-當前代碼做用域。最直接的就是隱式定義和當前代碼處在同一做用域中。
-當第一種解析方式沒有找到合適的隱式轉換時,編譯器會繼續在隱式參數類型的隱式做用域裏查找。一個類型的隱式做用域指的是與該類型相關聯的全部的伴生對象。code

對於一個類型T它的隱式搜索區域包括以下:
-假如T是這樣定義的:T with A with B with C,那麼A, B, C的伴生對象都是T的搜索區域。
-若是T是類型參數,那麼參數類型和基礎類型都是T的搜索部分。好比對於類型List[Foo],List和Foo都是搜索區域
-若是T是一個單例類型p.T,那麼p和T都是搜索區域。
-若是T是類型注入p#T,那麼p和T都是搜索區域。對象

因此,只要在上述的任何一個區域中搜索到合適的隱式轉換,編譯器均可以使編譯經過。

看兩個例子:

  1. 經過類型參數得到隱式做用域
scala> implicit val i: Int = 1 i: Int = 1 scala> implicitly[Int] res11: Int = 1 
  1. 經過嵌套得到隱式做用域
object Foo { trait Bar implicit val bar = new Bar { override def toString = "Foo`s Bar" } } object Test extends App { import Foo.Bar class B extends Bar def m(implicit bar: Bar) = println(bar.toString) m } 

經常使用法

轉換類型爲指望的類型

scala> val i: Int = 3.5 <console>:7: error: type mismatch; found : Double(3.5) required: Int val i: Int = 3.5 ^ scala> implicit def double2Int(d: Double) = d.toInt warning: there was one feature warning; re-run with -feature for details double2Int: (d: Double)Int scala> val i: Int = 3.5 i: Int = 3 

當咱們嘗試把一個帶有精度的數字複製給Int類型時,編譯器會給出編譯錯誤,由於類型不匹配。當咱們建立了一個double to int的隱式轉換以後編譯正常經過。還有一種狀況是與新類型的操做。

case class Rational(n: Int, d: Int) { def +(r: Rational) = Rational(n + r.n, d + r.d) } implicit def int2Rational(v: Int) = Rational(v, 1) Rational(1, 1) + Rational(1, 1) 1 + Rational(1, 1) 

模擬新的語法

好比scala中的arrow(->)語法就是一個隱式轉換

implicit final class ArrowAssoc[A](private val self: A) extends AnyVal { @inline def -> [B](y: B): Tuple2[A, B] = Tuple2(self, y) def →[B](y: B): Tuple2[A, B] = ->(y) } 

類型類

類型類是一種很是靈活的設計模式,能夠把類型的定義和行爲進行分離,讓擴展類行爲變得很是方便。

@implicitNotFound("No member of type class NumberLike in scope for ${T}") trait Increasable[T] { def inc(t: T): T } object Increasable { implicit object IncreasableInt extends Increasable[Int] { def inc(t: Int) = t + 1 } implicit object IncreasableString extends Increasable[String] { def inc(t: String) = t + t } } def inc[T: Increasable](list: List[T]) = { val ev = implicitly[Increasable[T]] list.map(ev.inc) } inc(List(1, 2, 3)) inc(List("z", "a", "b")) 

隱式參數

當咱們在定義方法時,能夠把最後一個參數列表標記爲implicit,表示該組參數是隱式參數。一個方法只會有一個隱式參數列表,置於方法的最後一個參數列表。若是方法有多個隱式參數,只需一個implicit修飾便可。
當調用包含隱式參數的方法是,若是當前上下文中有合適的隱式值,則編譯器會自動爲改組參數填充合適的值。若是沒有編譯器會拋出異常。固然,標記爲隱式參數的咱們也能夠手動爲該參數添加默認值。def foo(n: Int)(implicit t1: String, t2: Double = 3.14)

隱式視圖

隱式視圖:把一種類型轉換爲其餘的類型,轉換後的新類型稱爲視圖類型。隱式視圖會用於如下兩種場景:當傳遞給函數的參數與函數聲明的類型不匹配時;

scala> def log(msg: String) = println(msg) log: (msg: String)Unit scala> log("hello world") hello world scala> log(123) <console>:9: error: type mismatch; found : Int(123) required: String log(123) ^ scala> implicit def int2String(i: Int): String = i.toString warning: there was one feature warning; re-run with -feature for details int2String: (i: Int)String scala> log(123) 123 

當調用foo.bar,而且foo中並無bar成員時(經常使用於豐富已有的類庫)。

scala> :pas
// Entering paste mode (ctrl-D to finish) class Strings(str: String) { def compress = str.filter(_ != ' ').mkString("") } implicit def strings(str: String): Strings = new Strings(str) // Exiting paste mode, now interpreting. warning: there was one feature warning; re-run with -feature for details defined class Strings strings: (str: String)Strings scala> " a b c d ".compress res0: String = abcd 

隱式類型

若是細心觀察上邊的compress的實現和文章開頭lines的實現,這兩段代碼實現功能所採用的思路是相似的。可是,兩端代碼的實現形式是有區別的。lines的實現採用了scala中的隱式類型特性。隱式類型是scala提供的一種語法糖,隱式類型仍是要轉換爲:類型+隱式視圖的形式(也就是compress的形式)。

 

參考《Scala in depth》,《Scala 編程》。

相關文章
相關標籤/搜索