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")