官方文檔: http://kotlinlang.org/docs/reference/nested-classes.html
1.嵌套類(Nested Classes)
類可以嵌套在其他類中,不能訪問外部類成員:
class Outer {
private val bar: Int = 1
class Nest {
//嵌套類不能訪問外部類成員,相當于java的static 靜態內部類
fun foo() = 2
}
}
fun main(args: Array<String>) {
//創建嵌套類Nest對象,不需要外部類Outer對象
println(Outer.Nest().foo()) //輸出2
}
2.內部類(Inner classes)
類標記為inner,可以訪問外部類成員:
class Outer {
private val bar: Int = 1
inner class Inner {
//內部類可以訪問外部類成員,可看作外部類對象的一個成員
fun foo() = bar
}
}
fun main(args: Array<String>) {
//創建內部類Inner對象,需要外部類Outer對象
val outer = Outer()
println(outer.Inner().foo()) //輸出1
}
3.匿名內部類(Anonymous inner classes)
用對象表達式,創建匿名內部類的實例:
window.addMouseListener(
object: MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
...
}
override fun mouseEntered(e: MouseEvent){
...
}
}
)
當接口僅有一個接口方法/函數,可用lambda表達式省略接口方法/函數:
val listener = ActionListener{
println("clicked") //lambda表達式-簡化的匿名內部類
}
簡書:http://www.lxweimin.com/p/7f8c7c535cc0
CSDN博客: http://blog.csdn.net/qq_32115439/article/details/73692072
GitHub博客:http://lioil.win/2017/06/24/Kotlin-nested-classes.html
Coding博客:http://c.lioil.win/2017/06/24/Kotlin-nested-classes.html