Kotlin 2 cheatsheet
Kotlin 2: Basics and null safety
7 common Kotlin 2 tasks.
Declare variables
val is read-only and var is mutable. Types are inferred.
val name = "Ada" // read-only
var score = 0 // mutable
score += 10
Insert values in strings
Use $name or ${expression} inside a string.
println("$name scored ${score * 2} points")
Handle nulls
A type with ? can be null. Use ?. to call safely, ?: for a default, and !! only when you are certain.
val nickname: String? = null
val length = nickname?.length ?: 0
Branch with when
when is a flexible switch that can be an expression.
val label = when (score) {
in 0..49 -> "low"
in 50..89 -> "ok"
else -> "high"
}
Define functions
Parameters can have defaults and be passed by name. Single-expression functions drop the braces.
fun greet(name: String, greeting: String = "Hello") = "$greeting, $name!"
greet("Ada", greeting = "Hi")
Check a type and use it
After an is check, Kotlin smart-casts the value to that type.
fun describe(x: Any) = when (x) {
is String -> "text of length ${x.length}"
is Int -> "number ${x + 1}"
else -> "something else"
}
Validate arguments and state
require checks arguments and check verifies state, both throwing on failure.
fun withdraw(amount: Int) {
require(amount > 0) { "amount must be positive" }
check(balance >= amount) { "insufficient funds" }
}