Skip to main content

Kotlin Reference

v1.0.0

Kotlin 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 / var
Basics

val x: T = value var y: T = value

val is immutable (read-only), var is mutable. Type inference works for both.

String templates
Basics

"Hello, ${'$'}name" / "${'$'}{expr}"

Embed variables or expressions directly in strings using $ or ${}.

when expression
Basics

when (x) { value -> expr else -> expr }

Replaces switch — exhaustive, supports patterns, ranges, and smart casts.

Ranges
Basics

1..10 / 1 until 10 / 10 downTo 1 step 2

Create ranges for iteration or containment checks.

Type checks & casts
Basics

is / !is / as / as?

Check types at runtime. Smart casts automatically narrow the type after an is check.

Destructuring
Basics

val (a, b) = pair

Unpack data classes, pairs, maps, and lists into individual variables.

Type aliases
Basics

typealias Name = ExistingType

Create a new name for an existing type — useful for complex generics.

Nullable type
Null Safety

val x: T? = null

Append ? to any type to allow null — the compiler tracks nullability.

Safe call (?. )
Null Safety

obj?.property / obj?.method()

Access a member only if the receiver is non-null — returns null otherwise.

Elvis operator (?:)
Null Safety

val result = x ?: default

Provide a fallback value when the left-hand side is null.

Non-null assertion (!!)
Null Safety

val result = x!!

Force-unwrap a nullable — throws NPE if null. Use only when you are certain.

Safe cast (as?)
Null Safety

val x: T? = obj as? T

Cast that returns null instead of throwing ClassCastException.

let scope function
Null Safety

obj?.let { it -> ... }

Execute a block only when the receiver is non-null — common null-safe pattern.

requireNotNull / checkNotNull
Null Safety

requireNotNull(value) { "msg" }

Throw IllegalArgumentException / IllegalStateException if value is null.

data class
Classes & Objects

data class Name(val p1: T, val p2: T)

Auto-generates equals, hashCode, toString, copy, and componentN functions.

sealed class / interface
Classes & Objects

sealed class Result { ... }

Restrict class hierarchies — all subclasses must be in the same file. Enables exhaustive when.

object / companion
Classes & Objects

object Singleton { ... } companion object { ... }

object is a singleton. companion object provides static-like members.

enum class
Classes & Objects

enum class Direction { NORTH, SOUTH, EAST, WEST }

Type-safe enums with properties and methods.

Interface & delegation
Classes & Objects

class A(b: B) : MyInterface by b

Implement interfaces by delegating to another object — avoids boilerplate.

Property delegation
Classes & Objects

val x by lazy { ... } var y by Delegates.observable(init) { ... }

Delegate property access to another object — lazy, observable, map-backed.

Extension function
Functions

fun T.name(): R { ... }

Add new functions to existing classes without inheritance or wrappers.

Lambda / higher-order
Functions

val f: (T) -> R = { x -> expr } fun op(block: (T) -> R)

Functions are first-class. Lambdas can be passed, returned, and stored.

Default & named args
Functions

fun greet(name: String = "World")

Parameters can have defaults. Callers can use named arguments for clarity.

Inline function
Functions

inline fun <reified T> name() { ... }

Inline eliminates lambda overhead. reified preserves generic type info at runtime.

Scope functions
Functions

let / run / with / apply / also

Execute a block in the context of an object — differ in receiver (this/it) and return value.

Operator overloading
Functions

operator fun T.plus(other: T): T

Define or override operators (+, -, *, [], invoke, etc.) for your types.

launch
Coroutines

launch { ... }

Start a new coroutine that does not return a result — fire-and-forget.

async / await
Coroutines

val deferred = async { ... } val result = deferred.await()

Start a coroutine that returns a Deferred<T> — call await() to get the result.

suspend function
Coroutines

suspend fun name(): T { ... }

A function that can be paused and resumed — can only be called from coroutines.

Dispatchers
Coroutines

Dispatchers.Main / IO / Default / Unconfined

Control which thread pool a coroutine runs on.

Flow
Coroutines

flow { emit(value) } .collect { value -> ... }

Cold asynchronous stream — emits values sequentially, supports operators.

CoroutineScope
Coroutines

coroutineScope { ... } supervisorScope { ... }

Structured concurrency — child coroutines are cancelled when the scope ends or fails.

List / Set / Map
Collections

listOf() / mutableListOf() setOf() / mapOf()

Immutable by default. Use mutableListOf / mutableMapOf for mutation.

map / filter / reduce
Collections

.map { ... } .filter { ... } .reduce { acc, x -> ... }

Functional transforms on collections — lazy with sequences, eager on lists.

Sequences
Collections

list.asSequence().map { }.filter { }.toList()

Lazy evaluation — process one element at a time through the chain. Efficient for large collections.

groupBy / associate
Collections

.groupBy { key } / .associateBy { key }

Transform collections into maps — groupBy produces Map<K, List<V>>.

flatMap / flatten
Collections

.flatMap { it.children }

Flatten nested collections or map each element to a list and flatten.

Destructuring in lambdas
Collections

.map { (key, value) -> ... }

Destructure pairs and map entries directly in lambda parameters.

ViewModel
Android Patterns

class MyViewModel : ViewModel() { ... }

Lifecycle-aware component that survives configuration changes. Use with StateFlow.

StateFlow / SharedFlow
Android Patterns

MutableStateFlow(initial) MutableSharedFlow()

StateFlow holds a current value (like LiveData). SharedFlow is for events.

Jetpack Compose basics
Android Patterns

@Composable fun MyScreen() { ... }

Declarative UI — composable functions describe UI that recomposes on state changes.

Room Database
Android Patterns

@Entity / @Dao / @Database

Type-safe SQLite abstraction with compile-time query verification.

Dependency injection (Hilt)
Android Patterns

@HiltViewModel / @Inject / @Module

Compile-time DI framework built on Dagger — standard for Android apps.

Navigation Compose
Android Patterns

NavHost(navController, startDestination) { composable("route") { ... } }

Declarative navigation graph for Jetpack Compose screens.