zoukankan      html  css  js  c++  java
  • 快学Scala 第八课 (嵌套类)

    嵌套类:

    class Human {
      class Student{
        val age = 10
      }
    }
    
    object ClassDemo {
      def main(args: Array[String]): Unit = {
        val h = new Human
        val s = new h.Student
        println(s.age)
      }
    }
    

    有时会遇到这种情况:

    class Human {
      class Student {
        def addS(s: Student) = {
          val ab = new ArrayBuffer[Student]()
          ab += s
        }
      }
    }
    
    object ClassDemo {
      def main(args: Array[String]): Unit = {
        val h = new Human
        val h2 = new Human
        val s = new h.Student
        val s2 = new h2.Student
        s.addS(s2)
      }
    }
    

    以上addS会报错,因为方法只能接收h.Student不能接收h2.Student。

    解决方法有2个:

    1. 类型投影

    import scala.collection.mutable.ArrayBuffer
    
    class Human {
      class Student {
        def addS(s: Human#Student) = {
          val ab = new ArrayBuffer[Human#Student]()
          ab += s
        }
      }
    }
    
    object ClassDemo {
      def main(args: Array[String]): Unit = {
        val h = new Human
        val h2 = new Human
        val s = new h.Student
        val s2 = new h2.Student
        s.addS(s2)
      }
    }
    

    2. 伴生对象

    object Human {
      class Student {
    
      }
    }
    
    class Human {
        def addS(s: Human.Student) = {
          val ab = new ArrayBuffer[Human.Student]()
          ab += s
        }
    }
    
    object ClassDemo {
      def main(args: Array[String]): Unit = {
        
        val h = new Human
        val s = new Human.Student
        val s2 = new Human.Student
        
        h.addS(s)
        h.addS(s2)
        
        
      }
    }
    

    嵌套类要访问外部类有2种方式:

    1. 外部类.this

    class Human {
      val name = "Sky"
      class Student {
        println(Human.this.name)
        def addS(s: Student) = {
          val ab = new ArrayBuffer[Student]()
          ab += s
        }
      }
    }
    

    2. “自身类型”

    class Human {
      outter =>
      class Student {
        println(outter.name)
        def addS(s: Student) = {
          val ab = new ArrayBuffer[Student]()
          ab += s
        }
      }
      
      val name = "Sky"
    }
    
  • 相关阅读:
    php 加反斜杠的原因与处理办法
    python2.7 正则表达式的学习
    关于thinkhphp3.1中废弃 preg_replace /e 修饰符
    python2.7 函数的参数学习
    Laravel中Homestead添加多站点时遇到问题
    安装pywin32时,出现找不到python27注册信息的解决办法
    递归例子
    在SUSE平台启动和关闭mysql服务
    SUSE11 安装mysql
    delphi调用dll动态库
  • 原文地址:https://www.cnblogs.com/AK47Sonic/p/7287198.html
Copyright © 2011-2022 走看看