Kotlin: More snippets – code examples
Hello World
fun main() {
println("Hello World!")
}No class wrapper, no semicolons: main can live directly at the top level.
Variables and Types
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
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
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
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
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 ?:
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
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
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
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
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
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
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
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].