1. 程式人生 > 實用技巧 >scala隱式轉換

scala隱式轉換

// 關鍵字:implicit
// 隱式函式必須要在作用域範圍內定義
// 隱式轉換函式的 函式名自定義
// 隱式函式可以有多個,但是不能有重複的(函式名不能有重複,引數不能有重複)
// 程式碼中有下劃線的地方表示使用了隱式轉換
implicit def f1(d: Double): Int { d.toInt}  // 將double型別資料轉換為int型
implicit def f2(d: Float): Int { d.toInt}

// 將Double或Float資料賦值給 int 型,呼叫了隱式轉換
val num: Int = 3.5 // 底層編譯 f1$1(3.5)

/////////////////////////////////////////////////////////////////////////////
// 可以通過隱式行數豐富類庫的功能,比如
// 定義一個ms物件,只有insert方法
class MS{
    def insert(): Unit = {
        println("insert")
    }
}

// 再定義一個db物件,有delete方法
class DB {
    def delete(): Unit = {
        println("delete")
    }
}

// 定義隱式函式,返回 DB物件
implicit def addDelete(ms: MS): DB = {
    new DB
}

val ms = new MS
ms.insert()  // ms物件的方法
ms.delete()  // 隱式函式中的db的方法