Scala總共有三個地方會使用隱式定義:函數
寫過HBase的時候,都知道要寫大量的Bytes.toBytes()吧,那麼使用隱式轉換吧。code
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初始化的->
標識符嗎?這麼騷的操做也是隱式轉換乾的ci
若是你常常要構造某個類,那麼隱式的騷操做就能夠這麼幹。作用域
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")