KtKotlin

Kotlin: More snippets – code examples

Contents

Hello World

Basics#print#output#mainCompare in all languages
Use case: A first test of whether the compiler or playground works.
fun main() {
    println("Hello World!")
}

No class wrapper, no semicolons: main can live directly at the top level.

Variables and Types

Basics#val#var#type#templateCompare in all languages
Use case: Store values; protect immutable values with val.
fun main() {
    val name = "Ada"        // val: immutable
    var alter = 36          // var: mutable
    val groesse = 1.68
    val aktiv = true
    alter += 1
    println("$name $alter $groesse $aktiv")
    println(alter::class.simpleName)
}

Types are inferred; $name inserts variables into text. Output: Ada 37 1.68 true and Int.

try / catch / finally

Error handling#try#catch#exceptionCompare in all languages
Use case: Guard user input or network access without the program crashing.
fun main() {
    try {
        val zahl = "abc".toInt()
        println(zahl)
    } catch (e: NumberFormatException) {
        println("Invalid: ${e.message}")
    } finally {
        println("Cleaning up")
    }
}

Kotlin has no checked exceptions. try is an expression, and finally always runs. The message is For input string: "abc".

runCatching and require

Error handling#runcatching#result#require
Use case: Handle failing calls (parsing, network) without cascades of try/catch.
fun main() {
    val a = runCatching { "42".toInt() }.getOrDefault(-1)
    val b = runCatching { "abc".toInt() }.getOrDefault(-1)
    println("$a $b")
    val nenner = 0
    val r = runCatching { 10 / nenner }
    println(r.exceptionOrNull()?.message)
    println(runCatching { require(a > 100) { "a too small" } }.exceptionOrNull()?.message)
}

runCatching wraps success or exception in a Result. require checks preconditions. Output: 42 -1, / by zero, a too small.

Read and Write a File

Files#file#files#ioCompare in all languages
Use case: Save and load logs, configurations, or text data.
import java.io.File

fun main() {
    val datei = File("notizen.txt")
    datei.writeText("Line 1\nLine 2\n")
    datei.forEachLine { println(it.trim()) }
}

Kotlin adds writeText, readText, forEachLine, and more to java.io.File – no need to open and close by hand.

Read Large Files Line by Line

Files#file#uselines#sequence
Use case: Analyze log files without loading everything into memory.
import java.io.File

fun main() {
    val fehler = File("log.txt").useLines { zeilen ->
        zeilen.filter { "ERROR" in it }.count()
    }
    println("$fehler error lines")
}

useLines provides a lazy sequence and closes the file automatically afterwards.

Null Safety: ?. and ?:

Null safety#null#safe-call#elvis#let
Use case: Handle missing values (inputs, API fields) without a NullPointerException.
fun laenge(text: String?): Int = text?.length ?: 0

fun grussFuer(name: String?) =
    println(name?.let { "Hello $it!" } ?: "No name")

fun main() {
    println(laenge("Ada"))
    println(laenge(null))
    grussFuer("Ada")
    grussFuer(null)
}

?. calls only on non-null, ?: provides a fallback value. Output: 3, 0, Hello Ada!, No name.

Sealed Result with when

Modern Kotlin#sealed#when#result
Use case: Model success and failure as types instead of throwing exceptions.
sealed interface Ergebnis<out T> {
    data class Erfolg<T>(val wert: T) : Ergebnis<T>
    data class Fehler(val meldung: String) : Ergebnis<Nothing>
}

fun teile(a: Int, b: Int): Ergebnis<Int> =
    if (b == 0) Ergebnis.Fehler("Division by zero") else Ergebnis.Erfolg(a / b)

fun main() {
    for (b in listOf(2, 0)) {
        val text = when (val e = teile(10, b)) {
            is Ergebnis.Erfolg -> "Result: ${e.wert}"
            is Ergebnis.Fehler -> "Error: ${e.meldung}"
        }
        println(text)
    }
}

The compiler checks that when handles all subtypes (no else needed). Output: Result: 5 and Error: Division by zero.

Raw Strings & trimIndent

Strings#string#raw#trimindent
Use case: Write multi-line texts, paths, or regular expressions without escaping.
fun main() {
    val name = "Ada"
    val brief = """
        Hallo $name,
        dein Name hat ${name.length} Buchstaben.
    """.trimIndent()
    println(brief)
    val pfad = """C:\Users\ada\daten"""
    println(pfad)
}

No escaping applies inside """...""", and templates still work. trimIndent removes the common indentation. Output: Hallo Ada,, dein Name hat 3 Buchstaben., and C:Usersadadaten.

Counting Words

Strings#count#groupingby#text
Use case: Text analysis, e.g. the most frequent words in a document.
fun main() {
    val text = "this is a test this is fine"
    val zaehler = text.split(" ").groupingBy { it }.eachCount()
    println(zaehler)
    println(zaehler.entries.sortedByDescending { it.value }.take(2).map { it.key })
}

groupingBy { }.eachCount() is the Kotlin version of Python's Counter. Output: {this=2, is=2, a=1, test=1, fine=1} and [this, is].

Coroutines: async and await

Concurrency#coroutines#async#await
Use case: Start several independent queries (price, discount) in parallel and combine them.
import kotlinx.coroutines.*

suspend fun holePreis(): Int { delay(500); return 100 }
suspend fun holeRabatt(): Int { delay(500); return 20 }

fun main() = runBlocking {
    val preis = async { holePreis() }
    val rabatt = async { holeRabatt() }
    println("Final price: ${preis.await() - rabatt.await()}")
}

Both tasks run at the same time, so the result is ready after about 0.5 s instead of 1 s. Output: Final price: 80. Requires the kotlinx-coroutines library.

Flow

Concurrency#flow#coroutines#stream
Use case: Process data streams (sensors, live updates, database changes) asynchronously.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun zaehle(): Flow<Int> = flow {
    for (i in 1..3) {
        delay(100)
        emit(i)
    }
}

fun main() = runBlocking {
    zaehle().map { it * it }.collect { println(it) }
}

A Flow delivers values one after another and starts only on collect. Output: 1, 4, 9 (100 ms apart).

Delegated Properties: lazy and observable

Advanced#lazy#delegate#observable
Use case: Compute expensive values only when needed or react to value changes.
import kotlin.properties.Delegates

class Einstellungen {
    val teuer: String by lazy {
        println("computing...")
        "Result"
    }
    var lautstaerke: Int by Delegates.observable(5) { _, alt, neu ->
        println("Volume: $alt -> $neu")
    }
}

fun main() {
    val e = Einstellungen()
    println(e.teuer)
    println(e.teuer)
    e.lautstaerke = 8
}

lazy computes on first access and remembers the result. Output: computing..., Result, Result, Volume: 5 -> 8.

inline and reified

Advanced#reified#inline#generics
Use case: Type-dependent helper functions (filtering by type, JSON parsing) with type information at runtime.
inline fun <reified T> List<*>.nurTyp(): List<T> = filterIsInstance<T>()

fun main() {
    val gemischt = listOf(1, "two", 3, "four", 5.0)
    println(gemischt.nurTyp<String>())
    println(gemischt.nurTyp<Int>())
}

With inline and reified, the type T remains known at runtime. Output: [two, four] and [1, 3].