双刃剑,可以简化代码,但是会增加维护成本
- 实战
import java.io.File
//import ImplicitAspect._
/**
* Created by lihaiwo on 2019/9/20.
*/
object ImplicitApp extends App{
// 定义隐转换函数式
// implicit def man2superman(man:Man):Superman = new Superman(man.name)
//
// val man = new Man("pk")
// man.fly()
// implicit def file2richfile(file:File):RichFile = new RichFile(file)
// val file = new File("")
// val txt = file.read()
// println(txt)
// 隐式参数
def testParam(implicit name:String): Unit ={
println(name + "------------")
}
// testParam("zhang")
implicit val name ="im name"
testParam
}
class Man(val name:String) {
def eat(): Unit = {
println("eat")
}
}
class Superman(val name:String) {
def fly(): Unit = {
println("fly")
}
}
class RichFile(val file:File) {
def read() = {
scala.io.Source.fromFile(file.getPath).mkString
}
}
- 隐式转换切面封装
import java.io.File
/**
* Created by lihaiwo on 2019/9/20.
*/
object ImplicitAspect {
implicit def man2superman(man:Man):Superman = new Superman(man.name)
implicit def file2richfile(file:File):RichFile = new RichFile(file)
}
- 隐式类转换
/**
* 隐式类
*/
object ImplicitClassApp extends App{
implicit class Calculator(x:Int) {
def add(a:Int) = a + x
}
println(1.add(3))
}
网友评论