二次编译实现隐式转换: 当编译器第一次编译失败的时候,会在当前的环境中查找能让代码编译通过的方法

1.1 隐式函数

传统做法

  1. object Test01_Demo {
  2. def main(args: Array[String]): Unit = {
  3. var new12 = new MyRichInt(12)
  4. println(new12.isMax(13))
  5. }
  6. }
  7. class MyRichInt(val arg:Int){
  8. def isMax(i:Int): Int ={
  9. if(arg<i) i else arg
  10. }
  11. def isMin(i:Int):Int={
  12. if(arg>i) i else arg
  13. }
  14. }

隐式转换

  1. object Test01_Demo {
  2. def main(args: Array[String]): Unit = {
  3. implicit def cons(a:Int): MyRichInt ={ //能将Int转成MyRichInt
  4. new MyRichInt(a)
  5. }
  6. println(12.isMax(13))
  7. }
  8. }
  9. class MyRichInt(val arg:Int){
  10. def isMax(i:Int): Int ={
  11. if(arg<i) i else arg
  12. }
  13. def isMin(i:Int):Int={
  14. if(arg>i) i else arg
  15. }
  16. }

1.2 隐式类

隐式类不能是一个独立类,必须是一个内部类

  1. object Test01_Demo {
  2. def main(args: Array[String]): Unit = {
  3. println(12.isMin2(14))
  4. implicit class MyRichInt2(var a:Int){
  5. def isMax2(b:Int):Int={
  6. if(a<b) b else a
  7. }
  8. def isMin2(b:Int):Int={
  9. if(a>b) b else a
  10. }
  11. }
  12. }
  13. }

1.3 隐式参数

寻找匹配的是类型而不是参数名 隐式参数 会覆盖默认值、遵循柯里化规则

  1. object Test02_Demo {
  2. def main(args: Array[String]): Unit = {
  3. implicit var x:Int = 13
  4. var d = new Demo()
  5. d.xiXi
  6. }
  7. }
  8. class Demo {
  9. implicit var s:Int = 19
  10. def xiXi(implicit a:Int): Unit ={
  11. println(a)
  12. }
  13. }

简略写法

  1. object Test02_Demo {
  2. def main(args: Array[String]): Unit = {
  3. implicit var x:Int = 13
  4. var d = new Demo()
  5. d.haHa
  6. }
  7. }
  8. class Demo {
  9. implicit var s:Int = 19
  10. def haHa(): Unit ={
  11. println("hi,+implicitly[Int]) // 参数必须是当前代码的作用域
  12. }
  13. }

image.png