Kotlin Standard Library

Essential functions and utilities built into Kotlin

📚 What is Kotlin Standard Library?

The Kotlin Standard Library provides essential functions, collections, and utilities that make programming easier. It includes powerful tools for working with data, collections, strings, and more built right into the language.


// Standard library functions in action
val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.map { it * 2 }
val evens = numbers.filter { it % 2 == 0 }

println("Doubled: $doubled")  // [2, 4, 6, 8, 10]
println("Evens: $evens")      // [2, 4]
                                    

Standard Library Categories

📋

Collections

Lists, sets, maps with powerful operations

listOf(1, 2, 3).map { it * 2 }
🔤

String Operations

Text manipulation and formatting

"hello".capitalize()
"a,b,c".split(",")
🔧

Scope Functions

let, run, with, apply, also

person.apply {
    name = "Alice"
    age = 25
}
🔢

Math & Ranges

Mathematical operations and ranges

1..10
kotlin.math.max(5, 10)

🔹 Collection Operations

Powerful functions for working with collections:

fun main() {
    val fruits = listOf("apple", "banana", "cherry", "date", "elderberry")
    
    // Transform collections
    val uppercased = fruits.map { it.uppercase() }
    println("Uppercase: $uppercased")
    
    // Filter collections
    val longNames = fruits.filter { it.length > 5 }
    println("Long names: $longNames")
    
    // Find elements
    val firstLong = fruits.find { it.length > 5 }
    println("First long name: $firstLong")
    
    // Group elements
    val grouped = fruits.groupBy { it.first() }
    println("Grouped by first letter: $grouped")
    
    // Aggregate operations
    val totalLength = fruits.sumOf { it.length }
    println("Total length: $totalLength")
    
    // Check conditions
    val allLowercase = fruits.all { it == it.lowercase() }
    println("All lowercase: $allLowercase")
}

Output:

Uppercase: [APPLE, BANANA, CHERRY, DATE, ELDERBERRY]

Long names: [banana, cherry, elderberry]

First long name: banana

Grouped by first letter: {a=[apple], b=[banana], c=[cherry], d=[date], e=[elderberry]}

Total length: 31

All lowercase: true

🔹 String Operations

Built-in string manipulation functions:

fun main() {
    val text = "  Hello, Kotlin World!  "
    
    // Basic operations
    println("Original: '$text'")
    println("Trimmed: '${text.trim()}'")
    println("Uppercase: '${text.uppercase()}'")
    println("Lowercase: '${text.lowercase()}'")
    
    // String checks
    println("Contains 'Kotlin': ${text.contains("Kotlin")}")
    println("Starts with 'Hello': ${text.trim().startsWith("Hello")}")
    println("Ends with '!': ${text.trim().endsWith("!")}")
    
    // String manipulation
    val replaced = text.replace("World", "Universe")
    println("Replaced: '$replaced'")
    
    val parts = "apple,banana,cherry".split(",")
    println("Split result: $parts")
    
    val joined = parts.joinToString(" | ")
    println("Joined: $joined")
    
    // String templates and formatting
    val name = "Alice"
    val age = 25
    println("Formatted: ${name.padEnd(10)} is $age years old")
}

Output:

Original: ' Hello, Kotlin World! '

Trimmed: 'Hello, Kotlin World!'

Uppercase: ' HELLO, KOTLIN WORLD! '

Lowercase: ' hello, kotlin world! '

Contains 'Kotlin': true

Starts with 'Hello': true

Ends with '!': true

Replaced: ' Hello, Kotlin Universe! '

Split result: [apple, banana, cherry]

Joined: apple | banana | cherry

Formatted: Alice is 25 years old

🔹 Scope Functions

Functions that execute code blocks in the context of an object:

data class Person(var name: String = "", var age: Int = 0, var city: String = "")

fun main() {
    // let - transform object and return result
    val nameLength = Person("Alice", 25).let { person ->
        println("Processing ${person.name}")
        person.name.length  // Return value
    }
    println("Name length: $nameLength")
    
    // apply - configure object and return the object
    val person = Person().apply {
        name = "Bob"
        age = 30
        city = "New York"
    }
    println("Person: $person")
    
    // also - perform side effects and return the object
    val numbers = mutableListOf(1, 2, 3).also { list ->
        println("Original list: $list")
        list.add(4)
    }
    println("Modified list: $numbers")
    
    // run - execute code block and return result
    val result = run {
        val a = 10
        val b = 20
        a + b  // Return value
    }
    println("Result: $result")
    
    // with - operate on object without extension
    val message = with(person) {
        "Hello, my name is $name, I'm $age years old and live in $city"
    }
    println(message)
}

Output:

Processing Alice

Name length: 5

Person: Person(name=Bob, age=30, city=New York)

Original list: [1, 2, 3]

Modified list: [1, 2, 3, 4]

Result: 30

Hello, my name is Bob, I'm 30 years old and live in New York

🔹 Ranges and Progressions

Work with ranges of values efficiently:

fun main() {
    // Basic ranges
    val range1 = 1..10
    val range2 = 1 until 10  // Excludes 10
    val range3 = 10 downTo 1
    
    println("1..10 contains 5: ${5 in range1}")
    println("1 until 10: ${range2.toList()}")
    println("10 downTo 1: ${range3.toList()}")
    
    // Step ranges
    val evenNumbers = 2..20 step 2
    println("Even numbers: ${evenNumbers.toList()}")
    
    val countdown = 10 downTo 0 step 2
    println("Countdown: ${countdown.toList()}")
    
    // Character ranges
    val alphabet = 'a'..'z'
    println("Alphabet contains 'm': ${'m' in alphabet}")
    
    // Using ranges in loops
    print("Counting: ")
    for (i in 1..5) {
        print("$i ")
    }
    println()
    
    // Range functions
    val numbers = listOf(3, 1, 4, 1, 5, 9, 2, 6)
    println("Numbers in range 2..5: ${numbers.filter { it in 2..5 }}")
    
    // Coerce values to range
    println("Coerce 15 to 1..10: ${15.coerceIn(1..10)}")
    println("Coerce -5 to 1..10: ${(-5).coerceIn(1..10)}")
}

Output:

1..10 contains 5: true

1 until 10: [1, 2, 3, 4, 5, 6, 7, 8, 9]

10 downTo 1: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Even numbers: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Countdown: [10, 8, 6, 4, 2, 0]

Alphabet contains 'm': true

Counting: 1 2 3 4 5

Numbers in range 2..5: [3, 4, 5, 2]

Coerce 15 to 1..10: 10

Coerce -5 to 1..10: 1

🧠 Test Your Knowledge

Which scope function returns the object itself after applying operations?