一、隐式类概念
所谓隐式类: 就是对类增加implicit 限定的类,其作用主要是对类的加强!
如:
implicit class ImpInt(tmp:Int){
def add(tmp2: Int) = tmp + tmp2
}
class 前面的 implicit ,通过这个隐式类,就可以让Int型数据具有 add 方法。
二、隐式类型实例
import scala.io.Source
import java.io.File
/**
* 隐式类
* 其作用主要是对类的加强
*
* Created by zhiwang on 2015/7/22.
*/
object Implicit_Class {
import Context_Helper._
def main(args: Array[String]) {
println( 1.add(2)) //在当前作用域中寻找 将Int(1) 作为变量的类同时具有add 的方法的类,如有,则执行
println(new File("I:\\aa.txt").read()) //在当前作用域中寻找 将File 作为变量的类同时具有read的方法的类,如有,则执行
}
}
object Context_Helper{
implicit class ImpInt(tmp:Int){
def add(tmp2: Int) = tmp + tmp2
}
implicit class FileEnhance(file:File){
def read() = Source.fromFile(file.getPath).mkString
}
}
三、执行过程分析
- 当 1.add(2) 时,scala 编译器不会立马报错,而检查当前作用域有没有 用implicit 修饰的,同时可以将Int作为参数的构造器,并且具有方法add的类,经过查找 发现 ImpInt 符合要求
- 利用隐式类 ImpInt 执行add 方法
参考资料
- 百度云盘 第63讲:Scala中隐式类代码实战详解
- 腾讯微云 第63讲:Scala中隐式类代码实战详解
另外
欢迎广大Spark爱好者学习交流.也欢迎广大学习爱好者加入
DT大数据梦工厂交流群:462923555
DT大数据微信公众账号:DT_Spark