KOTLIN · 객체지향
내부 클래스 (Inner Class)
inner 키워드를 붙이면 외부 클래스의 인스턴스에 접근할 수 있는 내부 클래스가 됩니다.
객체지향중급inner-classouter-referencethis-qualified
핵심 설명
inner 키워드를 붙이면 외부 클래스의 인스턴스에 접근할 수 있는 내부 클래스가 됩니다.
Kotlin code
class RecyclerView(val items: List<String>) {
inner class ViewHolder(val position: Int) {
// 외부 클래스의 items에 접근 가능
fun bind() {
val item = items[position]
println("바인딩[$position]: $item")
}
// this@Outer로 외부 인스턴스 참조
fun getParentInfo() =
"RecyclerView(총 ${this@RecyclerView.items.size}개)"
}
fun createHolders(): List<ViewHolder> =
items.indices.map { ViewHolder(it) }
}
fun main() {
val rv = RecyclerView(listOf("사과", "바나나", "체리"))
val holders = rv.createHolders()
holders.forEach { it.bind() }
println(holders.first().getParentInfo())
}학습 팁
this@OuterClass 문법으로 외부 클래스의 this에 명시적으로 접근할 수 있습니다.
주의할 점
inner class는 외부 인스턴스를 참조하므로 외부 객체가 GC되지 않을 수 있습니다. Android에서 Activity 내부의 inner class는 메모리 누수 원인이 됩니다.
자주 묻는 질문
내부 클래스 (Inner Class)란 무엇인가요?
inner 키워드를 붙이면 외부 클래스의 인스턴스에 접근할 수 있는 내부 클래스가 됩니다.
내부 클래스 (Inner Class) 학습 시 주의할 점은 무엇인가요?
inner class는 외부 인스턴스를 참조하므로 외부 객체가 GC되지 않을 수 있습니다. Android에서 Activity 내부의 inner class는 메모리 누수 원인이 됩니다.
Continue Learning
Kotlin 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.