Kotlin, lesson 7
One variable holds one value. To work with a whole bunch of values, like every score in a game or every item in a cart, you put them in a collection. Kotlin's three everyday collections are the list, the set and the map.
A list keeps items in order, allows duplicates, and lets you reach each item by its index, starting at 0.
Asking for an index that doesn't exist, like planets[3] here, stops the program with an
error, so keep indexes between 0 and size - 1.
listOf gives a read-only list: you can look but not change it. When you need to add or
remove items, use mutableListOf:
Note that cart is a , yet we changed its contents. means the always points
to the same list; whether the list itself can change depends on its type. Prefer read-only
collections unless you need to modify them, so nobody changes them by accident.
2 exercises to try what you just read.
valvalTo start with an empty mutable list, tell Kotlin what it will hold:
mutableListOf<Int>().
Lists come with many ready-made functions, so you rarely need to write a loop for common jobs:
max() and min() throw an error on an empty list, so only call them when there is at least
one item.
A set holds each value at most once. Adding a value that is already there does nothing. Sets are great for questions like "have I seen this before?":
A map stores key → value pairs, like a dictionary that maps a word to its meaning. You
build pairs with to, look up a value with map[key], and set one with map[key] = value:
Looking up a missing key gives null rather than crashing. getOrDefault lets you pick a
fallback value instead, which is perfect for counting. The maps and sets made by
mapOf, mutableMapOf, setOf and mutableSetOf remember the order in which keys were
first added, so loops visit them in that order.
Read one line of race points, separated by spaces (at least one number). Print three lines:
If there are fewer than three scores, the podium shows all of them.
Sample input:
Sample output:
Read one line of lowercase words separated by single spaces. Count how many times each word
appears and print one line per distinct word, word: count, in the order each word first
appeared.
Sample input:
Sample output:
fun main() {
val planets = listOf("Mercury", "Venus", "Earth")
println(planets[0]) // Mercury
println(planets.size) // 3
println("Earth" in planets) // true
for (planet in planets) {
println(planet)
}
}val cart = mutableListOf("bread", "milk")
cart.add("eggs") // [bread, milk, eggs]
cart.remove("milk") // [bread, eggs]
cart[0] = "bagels" // replace by index
println(cart) // [bagels, eggs]val temps = listOf(18, 25, 21, 30)
println(temps.sum()) // 94
println(temps.max()) // 30
println(temps.average()) // 23.5
println(temps.sorted()) // [18, 21, 25, 30]
println(temps.sortedDescending()) // [30, 25, 21, 18]
println(temps.take(2)) // [18, 25]
println(temps.joinToString(", ")) // 18, 25, 21, 30val visited = mutableSetOf("Paris", "Rome")
visited.add("Paris") // already there, no change
println(visited.size) // 2fun main() {
val stock = mutableMapOf("apples" to 12, "pears" to 4)
stock["kiwis"] = 9 // add a new key
stock["pears"] = 3 // replace a value
println(stock["apples"]) // 12
println(stock["mangos"]) // null: no such key
println(stock.getOrDefault("mangos", 0)) // 0
for ((fruit, count) in stock) {
println("$fruit: $count")
}
}Players: <how many scores>
Best: <the highest score>
Podium: <the top three scores, highest first, separated by ", ">40 75 62 90 75Players: 5
Best: 90
Podium: 90, 75, 75the cat saw the dog and the cat ranthe: 3
cat: 2
saw: 1
dog: 1
and: 1
ran: 1