Standard library
- Kotlin course
- Intermediate
- Lesson 40/116
- 5 min
Learn extensions in the Kotlin standard library.
Standard library extensions
The Kotlin standard library ships with many extension functions. The best known are let, run, apply, also, with and the collection methods.
Example: "5".toIntOrNull()?.let { println(it * 2) }. Here toIntOrNull() is a String extension and let is a standard extension for nullable values. Calling listOf(1, 2, 3).map { it * 2 } returns [2, 4, 6]; map is also a standard extension. Standard library extensions make daily work short and readable.
map and let
Among the standard extensions, map and let are the most common. map transforms a collection; let works safely with nullable values.
Example: listOf(1, 2, 3).map { it * 2 } returns [2, 4, 6]. "5".toIntOrNull()?.let { println(it * 2) } first turns "5" into 5, then prints 10 when not null. it refers to the single lambda parameter. These extensions are standard for short, readable code.
Practice Using map and let
In main declare val nums = listOf(1, 2, 3); print the result of nums.map { it * 2 } with println. Also add the call "5".toIntOrNull()?.let { println(it * 2) }.
Starter code
// Define the nums list
// double each element with map and print
// double "5" with let and printSample solution
fun main() {
val nums = listOf(1, 2, 3)
println(nums.map { it * 2 })
"5".toIntOrNull()?.let { println(it * 2) }
}Expected output
[2, 4, 6] 10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the standard library extensions
| Term | Meaning |
|---|---|
"5".toIntOrNull() |
String extension |
?.let { ... } |
Nullable extension |
list.map { ... } |
Collection extension |
it |
Lambda parameter |
2 What does <code>listOf(1, 2, 3).map { it * 2 }</code> return?
- Throws an error
- [1, 2, 3]
- [3, 6, 9]
- [2, 4, 6] Correct answer
Explanation: map multiplies each element by 2; the result is [2, 4, 6].
3 Complete the map extension
val doubled = listOf(1, 2, 3).____ { it * 2 }
val doubled = listOf(1, 2, 3).map { it * 2 }
Explanation: map transforms each element.