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 | package exp { object Main { def main(args: Array[String]): Unit = { /* 隐式类型转换是编译器的动作,类型转换必须在编译时已经确定,所以 这个技术不能用于多态的类型判断,如下想实现整数和字符串调用不同的类型转换 不能实现.在同一个作用域中类型转换名不能重复,即使是转换的源类型不同也不 可以,如下stringSay 和 intSay 不可用相同的名称 */ implicit def stringSay(x:Any) = new { def say() = println ( "any say" ); } implicit def intSay(x:Int) = new { def say() = println ( "int say" ); } val m = List( "hello" , 38 ); m.foreach(p=>p.say); //any say , any say } } } |
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 | object Main { def main(args: Array[String]): Unit = { class A(val x:Int) { def +(other:A) = new A(this.x+other.x); override def toString = "A:" +this.x.toString; } class B(val x:Int) { def +(other:B) = new B(this.x+other.x); override def toString = "B:" +this.x.toString; } object A { def apply(x:Int) = new A(x); implicit def b2a(a:B) = new A(a.x); } object B { def apply(x:Int) = new B(x); implicit def a2b(a:A) = new B(a.x); } println (A( 1 )+B( 2 )); //优先在目标对象A中查找隐式类型转换,本例中优先将B转换为A (结果是A3),若找不到则将A转换成B(结果是B3) } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步