时间:2021-01-02 15:14:06 | 栏目:JAVA代码 | 点击:次
隐式转换和隐式参数
Scala总共有三个地方会使用隐式定义:
隐式规则
隐式转到到一个预期的类型
写过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")