XML Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
package com.lyzx.day18
class SpecialMan(name:String){ private val _name = name; def display(): Unit ={ println( "name="+_name) } } class SuperMan(val name:String){} class SpiderMan(val name:String){} class CarMan(val name:String){ def transformation()={println( "汽车人变形...")} } class Car(val name:String) /* 隐式准换 1、把一个类准换为另一个类 2、通过一个类调用另一个类的方法 * / class T2 { //1、把一个类准换为另一个类 def f1(person:SpecialMan): Unit ={ println( "f1......") } } object T2{ /* 隐式准换函数 implicit 有隐式的意思 当scala中的函数检查到传入的参数和定义的参数不同时会尝试着去执行隐式的转换 scala会找所有前面加implicit的函数 尝试着将传入的参数准换为定义的参数 T2.f1(...)的例子可以看到someting2SpecialMan执行(scala自动执行这个函数) * / implicit def someting2SpecialMan(obj:Object): SpecialMan = { if (obj.getClass == classOf[SuperMan]) { println( "SuperMan->SpecialMan") val superMan = obj.asInstanceOf[SuperMan] new SpecialMan(superMan.name) } else if (obj.getClass == classOf[SpiderMan]) { println( "SpiderMan->SpecialMan") val spiderMan = obj.asInstanceOf[SpiderMan] new SpecialMan(spiderMan.name) } else { null } } implicit def car2carMan(car:Object): CarMan ={ if(car.getClass == classOf[Car]){ println( "car->carMan") val carObj = car.asInstanceOf[Car] return new CarMan(carObj.name) }else{ println( "car.getClass="+car.getClass) println( "classOf[Car]="+classOf[Car]) println( "car->null") return null } } def main(args: Array[String]) { val t2 = new T2 // t2.f1(new SpiderMan( "")) // t2.f1(new SuperMan( "")) /* 当为f2方法传入Car类型的参数时,scala会尝试着把Car转换为CarMan 于是会尝试着执行car2carMan方法把Car转换为CarMan 并调用 * / val car = new Car( "霸天虎") car.transformation() } } |