CodeBlanks Logo Icon CodeBlanks

Standard library

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

Main.kt
// Define the nums list
// double each element with map and print
// double "5" with let and print

Sample solution

Main.kt
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

Question
val doubled = listOf(1, 2, 3).____ { it * 2 }
Answer
val doubled = listOf(1, 2, 3).map { it * 2 }

Explanation: map transforms each element.

All lessons in Intermediate