본문 바로가기

안드로이드/Kotlin

1. Effective Kotlin - Destructuring declaration

Destructuring declaration

직역하면 구조분해 선언이다. Old한 언어에서는 특정 함수나 작업의 결과 값을 하나만 받을 수 있다. 최신 언어의 경우 여러 결과를 동시에 받을 수 있다.

 

구조분해 선언을 활용하면 변수를 선언과 동시에 초기화할 수 있어 가독성 향상에 도움이 된다.

 

예시

fun updateWeather(degrees: Int) {
    val (description, color) = when {
        degrees < 5 -> "cold" to Color.BLUE
        degrees < 32 -> "mild" to Color.YELLOW
        else -> "hot" to Color.RED
    }
}