1. 程式人生 > >第64講Scala中的隱式類分析

第64講Scala中的隱式類分析

一、隱式類概念

所謂隱式類: 就是對類增加implicit 限定的類,其作用主要是對類的加強!

如:

  implicit class ImpInt(tmp:Int){
    def add(tmp2: Int) = tmp + tmp2
  }

class 前面的 implicit ,通過這個隱式類,就可以讓Int型資料具有 add 方法。

二、隱式型別例項


import scala.io.Source
import 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 } }

三、執行過程分析

  1. 當 1.add(2) 時,scala 編譯器不會立馬報錯,而檢查當前作用域有沒有 用implicit 修飾的,同時可以將Int作為引數的構造器,並且具有方法add的類,經過查詢 發現 ImpInt 符合要求
  2. 利用隱式類 ImpInt 執行add 方法

參考資料

另外
歡迎廣大Spark愛好者學習交流.也歡迎廣大學習愛好者加入
DT大資料夢工廠交流群:462923555
DT大資料微信公眾賬號:DT_Spark