Kotlin 2 cheatsheet

Kotlin 2: Collections and lambdas

6 common Kotlin 2 tasks.

Create collections

listOf, setOf and mapOf are read-only. Use mutableListOf and friends to change them.

val names = listOf("Ada", "Grace", "Linus")
val ages = mapOf("Ada" to 36, "Grace" to 45)
val tags = mutableSetOf("a")

Transform and filter

Chain operations on collections with lambdas. it names a single parameter.

val lengths = names.map { it.length }
val short = names.filter { it.length <= 3 }
val total = ages.values.sum()

Group, sort and count

Group items by a key, sort them and count matches.

val byLength = names.groupBy { it.length }
val sorted = names.sortedByDescending { it.length }
val count = names.count { it.startsWith("G") }

Process lazily

Sequences compute items on demand, which avoids intermediate lists for large pipelines.

val firstSquares = generateSequence(1) { it + 1 }
    .map { it * it }
    .filter { it % 2 == 1 }
    .take(3)
    .toList()

Use scope functions

let transforms an object, apply configures it, also adds a side effect, and run/with compute a result.

val result = name?.let { it.uppercase() }
val user = User(1, "Ada").also { println("created $it") }

Loop over a map

Destructure entries and ranges in for loops.

for ((name, age) in ages) println("$name is $age")
for (i in 1..3) println(i)

Was this page helpful?