快学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"
}

 

转载于:https://www.cnblogs.com/AK47Sonic/p/7287198.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值