Grundlagen
val x = 1 // unveränderlich
var y = 2 // veränderlich
const val C = 3 // Konstante (oberste Ebene)
val t: String? = null
fun f(a: Int, b: Int = 0): Int = a + bTypen
| Typ | Beispiel | Umwandeln |
|---|---|---|
Int, Long, Short, Byte | 42, 42L | toInt(), toLong() |
Double, Float | 3.14, 3.14f | toDouble() |
Boolean, Char, String | true, 'a', "x" | toString(), toBoolean() |
Any, Unit, Nothing | Wurzeltyp, "void", "kehrt nie zurück" | |
T? | nullbar | ?., ?:, !!, as? |
Kontrollfluss
if (a) x else y when (v) { 1 -> ..; in 2..5 -> ..; is String -> ..; else -> .. }
for (i in 1..10) {} for (i in 10 downTo 1 step 2) {} while () {} do {} while ()
break@label continue@label return@labelCollections
| Aufgabe | Funktion |
|---|---|
| Umformen | map, flatMap, filter, filterNotNull, zip |
| Zusammenfassen | sum, count, fold, reduce, average |
| Suchen | find, firstOrNull, any, all, none, contains |
| Sortieren | sorted, sortedBy, sortedWith, reversed |
| Gruppieren | groupBy, partition, associate, groupingBy().eachCount() |
| Teilen | take, drop, chunked, windowed, subList |
| Lazy | asSequence(), generateSequence, sequence { yield() } |
Klassen
class A(val x: Int, var y: Int = 0) : Basis(), Schnittstelle { init {..} }
open class Basis; abstract class Form; interface I { fun f() }
data class P(val a: Int) sealed class S enum class E { A, B }
object Singleton companion object { }
override fun / override val private set lateinit var by lazy { }Scope-Funktionen
| Objekt | Ergebnis | |
|---|---|---|
let | it | Blockwert |
run / with | this | Blockwert |
apply | this | Objekt |
also | it | Objekt |
Versionen: Hinweise
| Bereich | Älter | Neuer (Kotlin 1.4+) |
|---|---|---|
| Groß-/Kleinschreibung | toUpperCase(), capitalize() | uppercase(), replaceFirstChar { it.uppercase() } |
| Summen | sumBy { } | sumOf { } |
| Maxima | max()/maxBy nullbar | max()/maxBy nicht nullbar (ab 1.7), maxOrNull() |
| Interfaces | normal | fun interface (SAM), sealed interface |
| Listen | mutableListOf().apply { } | buildList { }, buildMap { } |
Häufige Fehler
| Meldung / Problem | Ursache |
|---|---|
| "Val cannot be reassigned" | val statt var verwendet |
| "Only safe (?.) or non-null asserted (!!.) calls are allowed" | nullbarer Typ ohne Prüfung |
| "Type mismatch: inferred type is Int but Long was expected" | keine automatische Zahlenumwandlung |
| "'when' expression must be exhaustive" | else oder alle Fälle ergänzen |
| Klasse lässt sich nicht erben | open fehlt |
NullPointerException trotz Kotlin | !! oder Java-Plattformtyp |
Weiterlernen
- Offizielle Seite kotlinlang.org mit "Kotlin Koans" und dem Playground
- Android Basics mit Compose (developer.android.com)
- Bücher: Kotlin in Action; Übungen: Kotlin Koans, Advent of Code
Merke
valvorvar, Typen ableiten lassen, Nullbarkeit im Typ- Collections-Funktionen statt Schleifen,
whenstatt Ketten - Data/Sealed Classes modellieren Daten und Zustände
- Coroutinen und Compose sind der moderne Android-Stack