zoukankan      html  css  js  c++  java
  • 隐式类型转换

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

      

  • 相关阅读:
    第二次结对编程作业
    第5组 团队展示
    第一次结对编程作业
    第一次个人编程作业
    51 Nod 1024 Set
    51 Nod 1007 dp
    YY的GCD 数学
    选课 树形背包dp
    运输问题 费用流
    分配问题 费用流
  • 原文地址:https://www.cnblogs.com/scala/p/3685988.html
Copyright © 2011-2022 走看看