Core Features
Collections and Lambdas
Master Kotlin's immutable and mutable collections with powerful functional operations.
Kotlin Collections
Kotlin distinguishes between read-only and mutable collections:
List<T>/MutableList<T>Set<T>/MutableSet<T>Map<K, V>/MutableMap<K, V>
Lambda Expressions
Kotlin lambdas use { parameters -> body } syntax. If the last parameter is a lambda, it can be placed outside parentheses.
Collection Operations
Kotlin provides a rich set of extension functions for collections, similar to Java Streams but more concise.
Example
kotlin
// Read-only list
val fruits = listOf("Apple", "Banana", "Cherry", "Date")
// Mutable list
val mutableFruits = mutableListOf("Apple", "Banana")
mutableFruits.add("Cherry")
mutableFruits.removeAt(0)
// Map
val capitals = mapOf("France" to "Paris", "Japan" to "Tokyo")
val mutableMap = mutableMapOf<String, Int>()
mutableMap["Alice"] = 95
mutableMap["Bob"] = 87
// Lambda expressions
val double = { x: Int -> x * 2 }
val add: (Int, Int) -> Int = { a, b -> a + b }
// Collection operations
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val evens = numbers.filter { it % 2 == 0 }
val doubled = numbers.map { it * 2 }
val sum = numbers.reduce { acc, n -> acc + n }
val sumAlt = numbers.sum()
// Chaining
val result = numbers
.filter { it % 2 == 0 }
.map { it * it }
.sortedDescending()
.take(3)
println(result) // [100, 64, 36]
// forEach
fruits.forEach { println(it) }
fruits.forEachIndexed { index, fruit -> println("$index: $fruit") }
// find, any, all, none
val firstLong = fruits.find { it.length > 5 }
val hasApple = fruits.any { it == "Apple" }
val allShort = fruits.all { it.length < 10 }
// groupBy
val byLength = fruits.groupBy { it.length }
// Sequence (lazy evaluation)
val lazyResult = (1..1_000_000)
.asSequence()
.filter { it % 2 == 0 }
.map { it * 3 }
.take(5)
.toList()Try it yourself — KOTLIN