快学Scala 第八课 (嵌套类)

Posted AK47Sonic

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了快学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"
}

 

以上是关于快学Scala 第八课 (嵌套类)的主要内容,如果未能解决你的问题,请参考以下文章

《快学Scala》第八章——继承

零基础学python第八课, 函数的基本使用参数返回值嵌套

零基础学python第八课, 函数的基本使用参数返回值嵌套

Python学习,第八课 - 函数

快学Scala 第十课 (包和包对象)

快学Scala--类