• 隐式类型转换


    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
                
          }
        }
    }    
    

      

    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)
            }
        }
    

      

  • 相关阅读:
    乱七八糟的
    C# 获取客户端电脑MAC 地址
    CheckInput
    gridview 合计行实现
    乱七八糟22
    jQuery UI CSS Framework
    CSS float和CSS clear
    smtp,POP3,IMAP
    960GridSystem
    CSS 清除浮动
  • 原文地址:https://www.cnblogs.com/scala/p/3685988.html
Copyright © 2020-2023  润新知