Kotlin Reference
v1.0.0Kotlin syntax, coroutines, null safety reference.
Quick reference for Kotlin syntax including null safety operators, coroutines, data classes, sealed classes, and extension functions.
How to use- →Browse categories or search for specific syntax (e.g. "launch", "?.let", "data class") to jump to the entry.
- →Click entries to expand examples — copy the snippet and adapt it in your Kotlin file.
- →Use the category tabs to explore related concepts together (Null Safety, Coroutines).
- →Try the Example picker (Simple → Advanced → Pro) to pre-fill a search for common patterns.
44 entries found
val x: T = value var y: T = value
val is immutable (read-only), var is mutable. Type inference works for both.
"Hello, ${'$'}name" / "${'$'}{expr}"
Embed variables or expressions directly in strings using $ or ${}.
when (x) { value -> expr else -> expr }
Replaces switch — exhaustive, supports patterns, ranges, and smart casts.
1..10 / 1 until 10 / 10 downTo 1 step 2
Create ranges for iteration or containment checks.
is / !is / as / as?
Check types at runtime. Smart casts automatically narrow the type after an is check.
val (a, b) = pair
Unpack data classes, pairs, maps, and lists into individual variables.
typealias Name = ExistingType
Create a new name for an existing type — useful for complex generics.
val x: T? = null
Append ? to any type to allow null — the compiler tracks nullability.
obj?.property / obj?.method()
Access a member only if the receiver is non-null — returns null otherwise.
val result = x ?: default
Provide a fallback value when the left-hand side is null.
val result = x!!
Force-unwrap a nullable — throws NPE if null. Use only when you are certain.
val x: T? = obj as? T
Cast that returns null instead of throwing ClassCastException.
obj?.let { it -> ... }
Execute a block only when the receiver is non-null — common null-safe pattern.
requireNotNull(value) { "msg" }
Throw IllegalArgumentException / IllegalStateException if value is null.
data class Name(val p1: T, val p2: T)
Auto-generates equals, hashCode, toString, copy, and componentN functions.
sealed class Result { ... }
Restrict class hierarchies — all subclasses must be in the same file. Enables exhaustive when.
object Singleton { ... } companion object { ... }
object is a singleton. companion object provides static-like members.
enum class Direction { NORTH, SOUTH, EAST, WEST }
Type-safe enums with properties and methods.
class A(b: B) : MyInterface by b
Implement interfaces by delegating to another object — avoids boilerplate.
val x by lazy { ... } var y by Delegates.observable(init) { ... }
Delegate property access to another object — lazy, observable, map-backed.
fun T.name(): R { ... }
Add new functions to existing classes without inheritance or wrappers.
val f: (T) -> R = { x -> expr } fun op(block: (T) -> R)
Functions are first-class. Lambdas can be passed, returned, and stored.
fun greet(name: String = "World")
Parameters can have defaults. Callers can use named arguments for clarity.
inline fun <reified T> name() { ... }
Inline eliminates lambda overhead. reified preserves generic type info at runtime.
let / run / with / apply / also
Execute a block in the context of an object — differ in receiver (this/it) and return value.
operator fun T.plus(other: T): T
Define or override operators (+, -, *, [], invoke, etc.) for your types.
launch { ... }
Start a new coroutine that does not return a result — fire-and-forget.
val deferred = async { ... } val result = deferred.await()
Start a coroutine that returns a Deferred<T> — call await() to get the result.
suspend fun name(): T { ... }
A function that can be paused and resumed — can only be called from coroutines.
Dispatchers.Main / IO / Default / Unconfined
Control which thread pool a coroutine runs on.
flow { emit(value) } .collect { value -> ... }
Cold asynchronous stream — emits values sequentially, supports operators.
coroutineScope { ... } supervisorScope { ... }
Structured concurrency — child coroutines are cancelled when the scope ends or fails.
listOf() / mutableListOf() setOf() / mapOf()
Immutable by default. Use mutableListOf / mutableMapOf for mutation.
.map { ... } .filter { ... } .reduce { acc, x -> ... }
Functional transforms on collections — lazy with sequences, eager on lists.
list.asSequence().map { }.filter { }.toList()
Lazy evaluation — process one element at a time through the chain. Efficient for large collections.
.groupBy { key } / .associateBy { key }
Transform collections into maps — groupBy produces Map<K, List<V>>.
.flatMap { it.children }
Flatten nested collections or map each element to a list and flatten.
.map { (key, value) -> ... }
Destructure pairs and map entries directly in lambda parameters.
class MyViewModel : ViewModel() { ... }
Lifecycle-aware component that survives configuration changes. Use with StateFlow.
MutableStateFlow(initial) MutableSharedFlow()
StateFlow holds a current value (like LiveData). SharedFlow is for events.
@Composable fun MyScreen() { ... }
Declarative UI — composable functions describe UI that recomposes on state changes.
@Entity / @Dao / @Database
Type-safe SQLite abstraction with compile-time query verification.
@HiltViewModel / @Inject / @Module
Compile-time DI framework built on Dagger — standard for Android apps.
NavHost(navController, startDestination) { composable("route") { ... } }
Declarative navigation graph for Jetpack Compose screens.