二次编译实现隐式转换: 当编译器第一次编译失败的时候,会在当前的环境中查找能让代码编译通过的方法
1.1 隐式函数
传统做法
object Test01_Demo {def main(args: Array[String]): Unit = {var new12 = new MyRichInt(12)println(new12.isMax(13))}}class MyRichInt(val arg:Int){def isMax(i:Int): Int ={if(arg<i) i else arg}def isMin(i:Int):Int={if(arg>i) i else arg}}
隐式转换
object Test01_Demo {def main(args: Array[String]): Unit = {implicit def cons(a:Int): MyRichInt ={ //能将Int转成MyRichIntnew MyRichInt(a)}println(12.isMax(13))}}class MyRichInt(val arg:Int){def isMax(i:Int): Int ={if(arg<i) i else arg}def isMin(i:Int):Int={if(arg>i) i else arg}}
1.2 隐式类
隐式类不能是一个独立类,必须是一个内部类
object Test01_Demo {def main(args: Array[String]): Unit = {println(12.isMin2(14))implicit class MyRichInt2(var a:Int){def isMax2(b:Int):Int={if(a<b) b else a}def isMin2(b:Int):Int={if(a>b) b else a}}}}
1.3 隐式参数
寻找匹配的是类型而不是参数名 隐式参数 会覆盖默认值、遵循柯里化规则
object Test02_Demo {def main(args: Array[String]): Unit = {implicit var x:Int = 13var d = new Demo()d.xiXi}}class Demo {implicit var s:Int = 19def xiXi(implicit a:Int): Unit ={println(a)}}
简略写法
object Test02_Demo {def main(args: Array[String]): Unit = {implicit var x:Int = 13var d = new Demo()d.haHa}}class Demo {implicit var s:Int = 19def haHa(): Unit ={println("hi,+implicitly[Int]) // 参数必须是当前代码的作用域}}

