Data Bundles

Kotlin splits bundles based on one key question: “Can this change?“


1. Line-up bundle: List

Immutable list (listOf)

val staticList = listOf("apple", "banana")
// staticList.add("grape") -> (Error!) cannot change it.

Mutable list (mutableListOf)

val shoppingList = mutableListOf("apple", "banana")

// Add
shoppingList.add("grape")

// Update
shoppingList[0] = "strawberry"

// Remove
shoppingList.removeAt(1)

println(shoppingList)

Translation:

Create a changeable string bundle called shoppingList
Add "grape"
Change box 0 to "strawberry"
Remove box 1

2. Labeled dictionary: Map

Mutable map (mutableMapOf)

val myInfo = mutableMapOf(
    "name" to "Alex",
    "city" to "Seoul"
)

// Add & update
myInfo["hobby"] = "Kotlin"

// Remove
myInfo.remove("city")

println(myInfo["name"])

Translation:

Create a changeable labeled bundle called myInfo
Put "Kotlin" under the "hobby" tag
Remove the "city" tag

Kotlin makes you decide from the start whether a bundle is mutable or not, which makes your data much safer to manage.