目录
- 概述
- 实践
- 代码
- 执行结果
- 结束
概述
隐式转换:偷偷的(隐式)对现有功能进行增强(转换)
实践
代码
package com.fun.scalaimport java.io.File
import scala.io.Sourceobject ImplicitApp {def main(args: Array[String]): Unit = {// implicit 2 = to 等价 :定义隐式转换函数// implicit def a2B(a:A):B =new B(a.)implicit def man2SuperMan(man: Man): SuperMan = new SuperMan(man.name)val man = new Man("测试")man.fly()implicit def file2RichFile(file: File) = new RichFile(file)val file = new File("data/wc.data")println(file.read())}
}class Man(val name: String)class SuperMan(val name: String) {def fly(): Unit = {println(s"$name fly ...")}
}/*** 隐式转换 常用命名:RichXxx*/
class RichFile(val file: File) {def read() = Source.fromFile(file.getPath, "utf-8").mkString
}
执行结果
结束
scala隐式转换 至此结束。