Kotlin에서 emptyArray, emptyList, emptyMap, emptySet는 각각 비어있는 collection 객체를 생성하는 함수들입니다. 이러한 함수들을 사용하면, collection을 초기화할 때 코드를 깔끔하고 직관적으로 작성할 수 있습니다. 이러한 빈 collection을 사용하는 경우, 초기화 단계에서 크기나 기본 값을 지정할 필요없이 즉시 사용 가능한 collection 객체를 얻을 수 있기 때문에 더 적은 코드로 원하는 기능을 구현할 수 있습니다.
emptyArray는 비어있는 array를 반환합니다. 크키가 0인 array를 반환하지만, array의 요소를 추가하거나 제거할 수 있습니다. array는 기본적으로 toString이 override되지 않기 때문에, array를 직접 출력하면 메모리 주소나 type이 출력됩니다. 그래서 내용물을 출력하려면 contentToString을 사용해야 합니다.
val emptyArrayExample = emptyArray<String>()
println(emptyArrayExample.contentToString()) // 빈 Array인 [] 출력
emptyList는 비어있는 list를 반환합니다. emptyList로 생성된 list는 읽기 전용이며, 요소를 추가하거나 제거할 수 없습니다.
val emptyListExample = emptyList<String>()
println(emptyListExample) // 빈 List인 [] 출력
emptyMap은 비어있는 map을 반환하며 key-value가 없습니다. emptyMap로 생성된 map은 읽기 전용이며, 요소를 추가하거나 제거할 수 없습니다.
val emptyMapExample = emptyMap<String, Int>()
println(emptyMapExample) // 빈 Map인 {} 출력
emptySet은 비어있는 set을 반환합니다. emptySet로 생성된 set은 읽기 전용이며, 요소를 추가하거나 제거할 수 없습니다.
val emptySetExample = emptySet<Int>()
println(emptySetExample) // 빈 Set인 [] 출력