2.2.6 데이터 객체 구조 분해하기

    프로퍼티가 N개 있는 데이터 클래스에는 component1부터 componentN이라는 함수가 자동으로 정의된다. 이 함수들은 클래스에 프로퍼티가 정의된 순서대로 각 프로퍼티에 접근하게 한다. 이런 함수를 주로 사용하는 경우가 객체의 구조 분해(destructing)다. 구조 분해를 사용하면 객체 프로퍼티에 훨씬 쉽게 접근할 수 있다.

    data class Person(val name: String, val registered: Instant = Instant.now())
    
    fun show(persons: List<Person>) {
        for ((name, date) in persons)
            println(name + "'s registration date: " + date)
    }
    
    fun main(args: Array<String>) {
        val persons = listOf(Person("Mike"), Person("Paul"))
        show(persons)
    }

    show 함수는 다음과 같다.

    fun show(persons: List<Person>) {
        for (person in persons)
            println(person.component1() + "'s registration date: " + person.component2())
    }

    코드를 보면 구조 분해를 통해 프로퍼티가 필요할 때마다 번거롭게 프로퍼티를 역참조할 필요가 없어서 코드가 더 명확하고 간결해짐을 알 수 있다.

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.