컬렉션의 가변(mutable)과 불변(immutable)

정리하자면, 불변 객체는 read-only 가변 객체는 read/write 가능임.

List

<aside> 💡 XXXOf 함수들은 원소들이 없다면, 타입추론이 안됨.

</aside>

fun main() {
    val myList = listOf(1 ,2, 3)
    val myMutableList = mutableListOf(1, 2, 3)
		val myListOfNotNull = listOfNotNull(1, 2, 3 , null)
    
    myMutableList.add(1) // O
    myList.add(1) // X
		println(myListOfNotNull) // [1, 2, 3]
		println(myListOfNotNull[3]) // Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
}

Set

fun main() {
    /** 가변 **/
    val hashSet = hashSetOf(1, 2, 3)
    val mutableSet = mutableSetOf(1, 2, 3)
    val sortedSet = sortedSetOf(1, 2, 3)
    val linkedSet = linkedSetOf(1, 2, 3)

    /** 불변 **/
    val set = setOf(1, 2, 3)

    mutableSet += 4 // add
    println(mutableSet) // [1, 2, 3, 4]
    mutableSet += 1
    println(mutableSet) // [1, 2, 3, 4]
    mutableSet -= 1 // remove
    println(mutableSet) // [2, 3, 4]
}

<aside> 💡 컬렉션에서 지원해주는 함수를 사용하여 각 컬렉션마다 기본 연산을 사용할 수 있음.

</aside>

Map