Kotlin

[Kotlin] 다양한 클래스(3)

Jyuni 2023. 5. 26. 00:48

Inner class

  • 자바에서는 클래스 안에 클래스를 정의하면 자동으로 내부 클래스가 됩니다.
  • 코틀린에서 클래스 안에 클래스를 선언하면 중첩 클래스입니다.
    • 내부 클래스로 만들고 싶다면 inner 키워드로 클래스를 선언해야 합니다.
    • 내부 클래스는 기본적으로 외부 클래스를 참조가 되지만 중첩 클래스는 참조가 불가능합니다.
// 중첩 클래스 (nested)
class OuterNested {
    private val num: Int = 1
    class Nested {
        // 중첩 클래스는 외부 클래스 멤버 참조 불가
        // fun foo() = num  // 불가능
        fun foo() = 10
    }
}

// 내부 클래스 (inner)
class OuterInner {
    private val num: Int = 1
    inner class Inner {
        private val num: Int = 20
        fun foo() = this.num
        // @를 사용하여 나의 this와 outer의 this를 구분한다.
        fun foos() = this@OuterInner.num
    }
}

fun main() {
    val nested = OuterNested.Nested().foo()
    val inner1 = OuterInner().Inner().foo()
    val inner2 = OuterInner().Inner().foos()
    println(nested)
    println(inner1)
    println(inner2)
}

/* 결과
10
20
1
*/