Kotlin Built-in Functions

Essential functions available in Kotlin standard library

🛠️ What are Built-in Functions?

Kotlin provides many built-in functions in its standard library for common operations like printing, string manipulation, collections processing, and type checking. These functions make coding more efficient and readable.


// Common built-in functions
println("Hello, World!")  // Print with newline
val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.map { it * 2 }  // Transform collection
                                    

Function Categories

📝

I/O Functions

Input and output operations

println("Hello")
print("No newline")
readLine()
📊

Collection Functions

Process lists, sets, and maps

map(), filter(), reduce()
forEach(), any(), all()
🔤

String Functions

Manipulate and check strings

length, isEmpty()
contains(), startsWith()
🔍

Type Functions

Check and convert types

is, as, as?
toString(), toInt()

🔹 I/O Functions

Functions for input and output operations:

fun demonstrateIO() {
    // Output functions
    println("This prints with a newline")
    print("This prints without newline ")
    print("- continues on same line\n")
    
    // Formatted output
    val name = "Alice"
    val age = 25
    println("Name: $name, Age: $age")
    printf("Formatted: Name is %s and age is %d\n", name, age)
    
    // Input function (commented for demo)
    // print("Enter your name: ")
    // val userInput = readLine() ?: "Unknown"
    // println("Hello, $userInput!")
    
    // Error output
    System.err.println("This is an error message")
}

Output:

This prints with a newline
This prints without newline - continues on same line
Name: Alice, Age: 25
Formatted: Name is Alice and age is 25

🔹 Collection Functions

Powerful functions for working with collections:

fun demonstrateCollections() {
    val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    
    // Transform collections
    val doubled = numbers.map { it * 2 }
    println("Doubled: $doubled")
    
    // Filter collections
    val evenNumbers = numbers.filter { it % 2 == 0 }
    println("Even numbers: $evenNumbers")
    
    // Reduce/fold operations
    val sum = numbers.reduce { acc, n -> acc + n }
    val product = numbers.fold(1) { acc, n -> acc * n }
    println("Sum: $sum, Product: $product")
    
    // Check conditions
    val hasEven = numbers.any { it % 2 == 0 }
    val allPositive = numbers.all { it > 0 }
    println("Has even: $hasEven, All positive: $allPositive")
    
    // Find elements
    val firstEven = numbers.first { it % 2 == 0 }
    val lastOdd = numbers.last { it % 2 == 1 }
    println("First even: $firstEven, Last odd: $lastOdd")
    
    // Group and partition
    val grouped = numbers.groupBy { it % 3 }
    val (evens, odds) = numbers.partition { it % 2 == 0 }
    println("Grouped by mod 3: $grouped")
    println("Evens: $evens, Odds: $odds")
}

Output:

Doubled: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Even numbers: [2, 4, 6, 8, 10]
Sum: 55, Product: 3628800
Has even: true, All positive: true
First even: 2, Last odd: 9
Grouped by mod 3: {1=[1, 4, 7, 10], 2=[2, 5, 8], 0=[3, 6, 9]}
Evens: [2, 4, 6, 8, 10], Odds: [1, 3, 5, 7, 9]

🔹 String Functions

Built-in functions for string manipulation:

fun demonstrateStrings() {
    val text = "  Hello, Kotlin World!  "
    
    // Basic properties
    println("Length: ${text.length}")
    println("Is empty: ${text.isEmpty()}")
    println("Is blank: ${text.isBlank()}")
    
    // Trimming and case
    val cleaned = text.trim()
    println("Trimmed: '$cleaned'")
    println("Uppercase: ${cleaned.uppercase()}")
    println("Lowercase: ${cleaned.lowercase()}")
    
    // Checking content
    println("Contains 'Kotlin': ${cleaned.contains("Kotlin")}")
    println("Starts with 'Hello': ${cleaned.startsWith("Hello")}")
    println("Ends with '!': ${cleaned.endsWith("!")}")
    
    // Splitting and joining
    val words = cleaned.split(" ")
    println("Words: $words")
    val rejoined = words.joinToString(" - ")
    println("Rejoined: $rejoined")
    
    // Replacing
    val replaced = cleaned.replace("Kotlin", "Programming")
    println("Replaced: $replaced")
    
    // Substring operations
    val substring = cleaned.substring(7, 13)  // "Kotlin"
    println("Substring: $substring")
    
    // String templates and formatting
    val name = "Alice"
    val age = 30
    val formatted = "Name: $name, Age: $age"
    println("Formatted: $formatted")
}

Output:

Length: 23
Is empty: false
Is blank: false
Trimmed: 'Hello, Kotlin World!'
Uppercase: HELLO, KOTLIN WORLD!
Lowercase: hello, kotlin world!
Contains 'Kotlin': true
Starts with 'Hello': true
Ends with '!': true
Words: [Hello,, Kotlin, World!]
Rejoined: Hello, - Kotlin - World!
Replaced: Hello, Programming World!
Substring: Kotlin
Formatted: Name: Alice, Age: 30

🔹 Type Checking and Conversion

Functions for working with types and conversions:

fun demonstrateTypes() {
    val value: Any = "123"
    
    // Type checking
    if (value is String) {
        println("Value is a String: $value")
        println("Length: ${value.length}")  // Smart cast
    }
    
    // Safe casting
    val stringValue = value as? String
    println("Safe cast result: $stringValue")
    
    val intValue = value as? Int
    println("Safe cast to Int: $intValue")  // null
    
    // Type conversions
    val numberString = "42"
    val number = numberString.toInt()
    val double = numberString.toDouble()
    val boolean = "true".toBoolean()
    
    println("String to Int: $number")
    println("String to Double: $double")
    println("String to Boolean: $boolean")
    
    // Converting back to strings
    println("Int to String: ${number.toString()}")
    println("Double to String: ${double.toString()}")
    
    // Null safety functions
    val nullableString: String? = null
    val length = nullableString?.length ?: 0
    println("Safe length: $length")
    
    // let, run, apply, also functions
    val result = "Hello".let { str ->
        str.uppercase().reversed()
    }
    println("Let result: $result")
    
    val person = Person("John", 25).apply {
        println("Created person: $name, age $age")
    }
}

data class Person(val name: String, val age: Int)

Output:

Value is a String: 123
Length: 3
Safe cast result: 123
Safe cast to Int: null
String to Int: 42
String to Double: 42.0
String to Boolean: true
Int to String: 42
Double to String: 42.0
Safe length: 0
Let result: OLLEH
Created person: John, age 25

🔹 Math and Utility Functions

Mathematical and utility functions:

import kotlin.math.*
import kotlin.random.Random

fun demonstrateMathAndUtils() {
    // Math functions
    val x = 16.0
    println("Square root of $x: ${sqrt(x)}")
    println("Power 2^3: ${2.0.pow(3.0)}")
    println("Absolute value of -5: ${abs(-5)}")
    println("Max of 10 and 20: ${max(10, 20)}")
    println("Min of 10 and 20: ${min(10, 20)}")
    
    // Rounding
    val decimal = 3.7
    println("Ceiling of $decimal: ${ceil(decimal)}")
    println("Floor of $decimal: ${floor(decimal)}")
    println("Round of $decimal: ${round(decimal)}")
    
    // Random numbers
    val randomInt = Random.nextInt(1, 11)  // 1 to 10
    val randomDouble = Random.nextDouble()
    println("Random int (1-10): $randomInt")
    println("Random double: $randomDouble")
    
    // Range functions
    val number = 5
    println("5 in range 1..10: ${number in 1..10}")
    println("Range 1 to 5: ${(1..5).toList()}")
    
    // Repeat function
    repeat(3) { index ->
        println("Repeat $index")
    }
    
    // Measure time
    val timeMillis = measureTimeMillis {
        // Simulate some work
        Thread.sleep(100)
    }
    println("Time taken: ${timeMillis}ms")
}

Output:

Square root of 16.0: 4.0
Power 2^3: 8.0
Absolute value of -5: 5
Max of 10 and 20: 20
Min of 10 and 20: 10
Ceiling of 3.7: 4.0
Floor of 3.7: 3.0
Round of 3.7: 4.0
Random int (1-10): 7
Random double: 0.8234567
5 in range 1..10: true
Range 1 to 5: [1, 2, 3, 4, 5]
Repeat 0
Repeat 1
Repeat 2
Time taken: 102ms

🧠 Test Your Knowledge

Which function is used to transform each element in a collection?