1. 程式人生 > 程式設計 >scala 隱式轉換與隱式引數的使用方法

scala 隱式轉換與隱式引數的使用方法

隱式轉換和隱式引數

Scala總共有三個地方會使用隱式定義:

  • 轉換到一個預期的型別
  • 對某個(成員)選擇接收端(欄位、方法呼叫等)的轉換
  • 隱式引數

隱式規則

  • 標記規則:只有標記為implicit的定義才可用。可標記任何變數、函式、物件
  • 作用域規則:被插入的隱式轉換必須是當前作用域的單個識別符號,或者跟隱式轉換的源型別或目標型別有關聯
  • 每次一個規則:每次只能有一個隱式定義被插入
  • 比如編譯器絕不會將x+y重寫為convert2(convert1(x))+y
  • 顯示優先規則:只要程式碼按編寫的樣子能通過型別檢查,就不嘗試隱式定義

隱式轉到到一個預期的型別

寫過HBase的時候,都知道要寫大量的Bytes.toBytes()吧,那麼使用隱式轉換吧。

object HBasePref {

 implicit def Str2Bytes(value: Any): Array[Byte] = value match {

  case str: String => Bytes.toBytes(str)
  case long: Long => Bytes.toBytes(long)
  case double:Double => Bytes.toBytes(double)
 }

 implicit def str2HBaseTableName(str: String): TableName = TableName.valueOf(str)
}

與新型別互相操作

你期望能夠執行1 + new Rational(1,2)這個程式碼,但int型別顯然沒有這個方法。用隱式轉換吧

implicit def intToRational(x:Int) = new Rational(1,1)

模擬新的語法

還記得Map初始化的->識別符號嗎?這麼騷的操作也是隱式轉換乾的

隱式類

如果你經常要構造某個類,那麼隱式的騷操作就可以這麼幹。

case class Rectangle(width,height)

implicit class RectangleMaker(width:Int) {
  def x(height:Int) = Rectangle(width,height)
}

val myRectangle = 3 x 4

隱式引數

class PreferredPromt(val preference:String)

object JoesPrefs {
  implicit val promt = new PreferredPrompt("Yes master>")}

object Greeter {
  def greet(name:String)(implicit prompt:PreferredPromt) = {
    println("Welcome," + name)
    println(prompt.preference)
  }
}

import JoesPrefs._

Greeter.greet("ljk")

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。