壹、隱式類概念
所謂隱式類: 就是對類增加implicit 限定的類,其作用主要是對類的加強!
如:
implicit class ImpInt(tmp:Int){
def add(tmp2: Int) = tmp + tmp2
}123
class 前面的?implicit?,通過這個隱式類,就可以讓Int型數據具有 add 方法。
二、隱式類型實例
import scala.io.Sourceimport java.io.File/**
* 隱式類
* 其作用主要是對類的加強
*
* Created by zhiwang on 2015/7/22.
*/object Implicit_Class {
import Context_Helper._ ?def main(args: Array[String]) {
println( 1.add(2)) ?//在當前作用域中尋找 將Int(1) 作為變量的類同時具有add 的方法的類,如有,則執行
println(new File("I:\\aa.txt").read()) //在當前作用域中尋找 將File 作為變量的類同時具有read的方法的類,如有,則執行
}
}object Context_Helper{
implicit class ImpInt(tmp:Int){
def add(tmp2: Int) = tmp + tmp2
}
implicit class FileEnhance(file:File){
def read() = Source.fromFile(file.getPath).mkString
}
}12345678910111213141516171819202122232425262728293031
三、執行過程分析
當 1.add(2) 時,scala 編譯器不會立馬報錯,而檢查當前作用域有沒有 用implicit 修飾的,同時可以將Int作為參數的構造器,並且具有方法add的類,經過查找 發現 ImpInt 符合要求
利用隱式類 ImpInt 執行add 方法