minstudio

3. 컬렉션 (List, Set, Map)

코틀린의 컬렉션은 자바와 달리 불변(Read-only)가변(Mutable)이 엄격하게 분리되어 있습니다.

listOf(), setOf(), mapOf()로 만든 컬렉션은 값을 추가하거나 삭제할 수 없습니다. 요소를 수정하려면 반드시 mutableListOf() 처럼 mutable이 붙은 함수를 사용해야 합니다. 이는 개발자의 실수로 데이터가 변경되는 버그를 원천 차단합니다.

fun main() {
    // 1. List (순서 보장, 중복 허용)
    // 읽기 전용(Immutable) 리스트
    val readOnlyList = listOf("Apple", "Banana", "Cherry")
    println("읽기 전용: " + readOnlyList)
    // readOnlyList.add("Orange") // 에러! add 메서드가 없습니다.

    // 가변(Mutable) 리스트
    val mutableList = mutableListOf("Apple", "Banana")
    mutableList.add("Cherry")
    println("수정 가능: " + mutableList)


    // 2. Map (Key-Value)
    // 'to' 라는 중위 연산자(Infix function)를 사용하여 직관적으로 키-값 쌍을 만듭니다.
    val menuPrices = mutableMapOf(
        "아메리카노" to 4000,
        "카페라떼" to 4500
    )
    
    // 값 추가 및 맵 접근 (배열처럼 대괄호 사용 가능!)
    menuPrices["바닐라라떼"] = 5000
    println("아메리카노 가격: " + menuPrices["아메리카노"])
}
3. 컬렉션 (List, Set, Map) | Minstudio