The Kotlin Standard Library
In this page:
String Utilities
The standard library provides many convenient string functions, such as .joinToString() to build a string from a collection, and .repeat() to repeat a string a given number of times.
Example: String Utilities
fun main() {
val fruits = listOf("apple", "banana", "cherry")
println(fruits.joinToString(", "))
println("ab".repeat(3))
}
Login to try C/C++/Java/PHP code in the editor
Numeric Utilities
Functions like .coerceIn(min, max) clamp a number to a given range, and .coerceAtLeast()/.coerceAtMost() clamp it to just one bound.
Example: Numeric Utilities
fun main() {
val value = 150
println("Clamped: ${value.coerceIn(0, 100)}")
println("At most 50: ${value.coerceAtMost(50)}")
}
Login to try C/C++/Java/PHP code in the editor
Collection Utilities Recap
The standard library's collection functions -- .map, .filter, .sorted, .groupBy, and many more -- cover the vast majority of everyday data transformation needs without a manual loop.
Example: Collection Utilities Recap
fun main() {
val numbers = listOf(5, 3, 8, 1, 9)
println("Sorted: ${numbers.sorted()}")
println("Max: ${numbers.max()}")
println("Chunked: ${numbers.chunked(2)}")
}
Login to try C/C++/Java/PHP code in the editor
What's Not in the Standard Library
Coroutines (kotlinx.coroutines), serialization (kotlinx.serialization), and date/time handling (kotlinx.datetime) are all separate kotlinx libraries maintained by JetBrains, requiring their own dependency, even though they feel like natural extensions of the language.
Example: What's Not in the Standard Library
fun main() {
// kotlin-stdlib alone is enough for everything in this example
val date = "2024-01-15"
val parts = date.split("-")
println("Year: ${parts[0]}, Month: ${parts[1]}, Day: ${parts[2]}")
}
Login to try C/C++/Java/PHP code in the editor
- Reimplementing common utilities, like finding the max of two numbers or joining a list into text, that the standard library already provides.
- Assuming every convenient function (like coroutines or serialization) is part of the standard library, when many are separate
kotlinxlibraries requiring their own dependency. - Not exploring collection, string, and scope function utilities before writing manual loops for tasks they already solve concisely.
- The Kotlin standard library (
kotlin-stdlib) ships with the compiler and provides collections, string utilities, scope functions, and more, with no extra dependency needed. - Libraries like
kotlinx.coroutines,kotlinx.serialization, andkotlinx.datetimeare separate from the standard library and must be added explicitly. - Common standard library helpers include
.joinToString(),.coerceIn(),.repeat(), and the scope functions covered earlier. - Checking the standard library first often avoids writing verbose manual logic for common tasks.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: