Skip to content

Kotlin Beyond the Basics

Glossary

135 terms from Kotlin Beyond the Basics, in plain words, each with the chapter that teaches it.

#

@DslMarker
An annotation that stops code in an inner builder block from quietly calling methods of an outer receiver.
@Serializable
`@Serializable` tells the plugin to generate JSON code for a class. `@SerialName` maps a differently named key, and bad input throws `SerializationException`.

A

actual
The platform-specific implementation of something declared with `expect`. Each target, such as `jvmMain` or `iosMain`, supplies its own `actual platformName()`.
annotation
A label starting with `@`, such as `@Serializable` or `@Test`, placed before a class, function or property. Tools like the compiler plugin or test runner read it.
Any
The top type: every non-null type is a kind of `Any`. `Any?` also accepts `null`.
Application (Ktor)
Ktor's class for the running server. The setup function `Application.module()` is an extension on it, where you install plugins and add routes.
apply
A scope function that runs a lambda with the object as `this` and returns the object, handy for setting up a new object. Builders use it to fill in a `Board` or `Section`.
arrange, act, assert
A common shape for a test: set up the input, run the code, then check the result.
array (JSON)
A list of values in square brackets in JSON, such as the `extras` list in an order line.
assertEquals
`kotlin.test` functions that check a result. `assertEquals(expected, actual)` passes if the two are equal (expected first), `assertIs<T>` checks the type and smart-casts, and `assertFailsWith<E> { }` passes only if the block throws an `E`.
associateBy
A collection function that builds a map from a key you choose to one item each, such as menu items by code.
asStateFlow
Gives a read-only `StateFlow` view of a private `MutableStateFlow`, so only the owning class can change the value.
async
Starts a coroutine that produces a result later. `await()` waits for that result, and any exception waits in the `Deferred` until then.
awaitAll
Waits for a list of `async` results and returns them in order, so several slow calls can overlap instead of running one after another.

B

BadRequestException
The exception Ktor's `call.receive` throws when a request body isn't valid for the expected class. Catch it and answer 400 Bad Request.
body (HTTP)
The content of an HTTP request or response, such as the JSON of an order.
bottom type
A type with no values, which fits anywhere. In Kotlin it is `Nothing`.
buffer
Flow operators for a slow collector. `buffer()` lets the flow run ahead, and `conflate()` skips missed values and keeps only the latest.
build.gradle.kts
The Kotlin-script build file where a Gradle project lists plugins and dependencies. `./gradlew run` and `./gradlew test` run the app and its tests.
builder
A function that creates an object and lets a lambda with a receiver fill it in, such as `menu { section { item(...) } }`.
buildString
Standard builders that give you a receiver to fill in one block, then return a read-only string, list or map.

C

call (Ktor)
Inside a Ktor handler, the object for the current request and its response. You read from it and answer with `call.respond`.
cancellation
Stopping a coroutine before it finishes. `job.cancel()` asks it to stop and `cancelAndJoin()` asks and waits.
CancellationException
The exception cancellation travels as. Catching a general `Exception` also catches it, so rethrow it to let the coroutine stop.
cast
Telling Kotlin to treat a value as another type with `as`. It throws an exception if the value isn't that type.
catch (Flow)
Flow operators: `catch { }` handles exceptions from the steps above it and can emit a fallback, and `onCompletion { }` runs when the flow ends, normally or not.
channel
A queue coroutines use to pass values: `send` puts one in and `receive` takes one out. `close()` says no more are coming.
client
A program that sends requests to a server, such as a browser, a phone app or the shop's website.
closure
A lambda that keeps the values from around it that it uses. Each `discount` lambda remembers its own `percent`.
cold flow
A cold flow runs its code only when collected, and again for each collector. A hot flow such as `StateFlow` exists and holds values whether or not anyone collects.
collect
`collect` receives each value of a flow, and `emit` sends one from inside a `flow { }` block. Both are suspend functions.
combine
Joins the latest values of two flows with a function, and emits again whenever either changes.
commonMain
Source set folders in Kotlin Multiplatform: `commonMain` is compiled for every target, `jvmMain` for the JVM only, `iosMain` for iOS.
Comparable
A standard interface whose `compareTo` function is what `<` and `>` call. A bound of `Comparable<T>` lets generic code compare values.
compiler plugin
An add-on to the Kotlin compiler that writes extra code while compiling. The serialization plugin generates the JSON code for `@Serializable` classes.
ContentNegotiation
The Ktor plugin that converts `@Serializable` classes to and from JSON, so `call.respond` and `call.receive` work with objects.
contravariant
A type parameter marked `in` is only taken in, never returned, so `Rule<Priced>` can stand in for `Rule<MenuItem>`.
cooperative
Cancellation is cooperative: a coroutine only stops where it checks, such as at `delay`, `isActive` or `ensureActive()`. A loop that never suspends never notices.
coroutine
A lightweight task that can pause and resume without blocking a thread. It is started with `launch`, `async` or `runBlocking`.
coroutine context
The settings a coroutine carries, such as its dispatcher, its `Job` and an optional name, joined with `+`.
CoroutineExceptionHandler
A coroutine context element that receives an exception from a failed `launch` instead of letting it print a crash report.
CoroutineScope
An object that owns coroutines, which you start with `launch` and `async`. Canceling it stops them all, and `GlobalScope` is discouraged because nothing cancels its coroutines.
covariant
A type parameter marked `out` is only returned, never taken in, so `Box<MenuItem>` counts as a `Box<Any>`.
curl
A command-line tool that sends HTTP requests. `-i` shows headers, `-X` sets the method, `-H` adds a header and `-d` sends a body.

D

data class
A class for holding data, such as `MenuItem`, with equality by value, `toString` and `copy` generated for it.
declaration-site variance
Declaration-site variance marks `in` or `out` on the class itself. Use-site variance marks it where the type is used, as in `MutableList<out Priced>`.
deserialization
Turning text such as JSON back into an object, done with `Json.decodeFromString`.
dispatcher
Decides which threads a coroutine runs on: `Default` for CPU work, `IO` for blocking waits on files or networks, and `Main` for the UI thread.
DSL
A small language for one job. In Kotlin it is ordinary code, built from lambdas with receivers, shaped to read like a description, as in `routing { get("/menu") { } }`.

E

Elvis operator
`?:` runs its right side when the left side is `null`, such as to give a fallback or `return` early.
endpoint
A method plus a path, such as `GET /menu`.
engine (Ktor)
The library inside a Ktor server that does the low-level network work of accepting connections and passing requests to your code. Netty is a common choice, selected with `embeddedServer(Netty, ...)`.
ensureActive
Ways a coroutine checks for cancellation: `isActive` is true until canceled, and `ensureActive()` throws `CancellationException` once canceled.
enum class
A class with a fixed set of values, such as `Status` with `PLACED` and `READY`. Serialization writes it by name.
expect
A declaration without a body in `commonMain`, saying common code needs something each platform provides via `actual`.

F

filterIsInstance
A standard library function that keeps only items of a given type, such as `filterIsInstance<Int>()`.
finally
A block that runs on the way out of a `try`, including on cancellation, so it suits switching things off.
flatMap
Maps each item to a list and joins the lists into one.
flow
A stream of values that arrive over time, built with `flow { }` and received with `collect`.
flowOn
Moves the flow steps above it to another dispatcher while `collect` stays on its own.
fold
Carries a running value through a collection, starting from a value you give. `reduce` starts from the first item.
function reference
A function used as a value, written with `::`, such as `lines.map(::checkLine)` or `MenuItem::priceCents`.

G

generic class
A class or function with a type parameter, so it works for any type, such as `Shelf<T>`.
groupBy
Maps each key to a list of the items that share it, such as wholesale lines grouped by café.

H

header
A labeled fact in an HTTP request or response. `Content-Type: application/json`, for example, says the body is JSON.
higher-order function
A function that takes or returns another function, such as `discount` returning a lambda.
HTTP
The way clients and servers talk. A request has a method, path, headers and sometimes a body, and the response has a status code, headers and a body.

I

ignoreUnknownKeys
A `Json { }` option that skips JSON keys the class doesn't have. Without it, an unexpected key stops decoding.
infix function
A one-parameter function marked `infix`, called between two values without dot or brackets, such as `"lat" costs 475` or `to`.
inline function
A function whose body, and the lambdas passed to it, are copied into each caller. `noinline` keeps one lambda parameter as an object.
install
The Ktor call that adds a plugin to the server, such as `install(ContentNegotiation) { json() }`.
IntelliJ IDEA
A JetBrains editor (IDE) for writing and running Kotlin code. Its **Alt+Enter** shortcut offers fixes for a red name, such as adding a missing import.
intermediate operator
An intermediate flow operator, such as `map`, returns a new flow and runs nothing. A terminal operator, such as `collect` or `toList`, starts the flow.

J

JDK
The Java Development Kit, the toolkit for building and running JVM programs; JDK 21 is a recent long-term-support version. It includes the JVM, the runtime that Kotlin code compiled for servers and desktops runs on.
Job
The handle for a running coroutine, used to wait with `join()` or stop with `cancel()`. A parent's Job isn't complete until all its children are.
join
Waits for a coroutine's `Job` to finish.
JSON
A text format for data using objects in `{}` with `"key": value` pairs, arrays in `[]`, strings, numbers, booleans and `null`.
JUnit
The standard test runner for the JVM. `useJUnitPlatform()` in Gradle tells it to run your tests.

K

kotest
A Kotlin test framework with its own style. In a `StringSpec`, each test is a string followed by a lambda, and `shouldBe` is an infix assertion.
Kotlin Multiplatform
One Kotlin codebase compiled for several targets, such as the JVM, Android, iOS, JavaScript and WebAssembly. It usually shares logic, not screens.
kotlin.test
Kotlin's test library. `@Test` marks a test function, and `@BeforeTest` marks setup that runs before each test.
kotlinx.coroutines
The JetBrains library that provides coroutines for Kotlin, including `launch`, `async`, dispatchers, `Mutex` and `Channel`. It is added to a Gradle project as a dependency, and a separate test library adds `runTest`.
kotlinx.serialization
JetBrains' library for converting between Kotlin objects and JSON, used through `Json.encodeToString` and `Json.decodeFromString`.
Ktor
JetBrains' Kotlin library for writing servers and clients, used to build Kettle & Crane's order API.

L

label
A name after `@`, such as `return@forEach` or `return@post`, saying which lambda a `return` leaves.
lambda with receiver
A lambda that runs as if it were a member of an object, the receiver, so `this` is that object. Its type looks like `Receipt.() -> Unit`.
lazy
Worked out only when needed, as in a sequence that does nothing until a last step asks.
localhost
A computer's name for itself, used to reach a server running on your own machine.
Logback
A logging library that prints Ktor's log to the console.

M

method (HTTP)
The verb of an HTTP request: `GET` reads something and `POST` sends something new.
MutableSharedFlow
A hot flow for events rather than state. It has no current value, sends each event to everyone collecting at that moment, and misses late collectors unless you set `replay`.
Mutex
A lock letting one coroutine at a time run a block. `withLock { }` waits its turn, suspending rather than blocking.

N

non-local return
A plain `return` inside an inline function's lambda that leaves the calling function, such as returning from `hasCode` inside `forEach`.
Nothing
The bottom type with no values. A function returning it never returns normally, and `throw` has this type.

O

operator function
A function marked `operator` that a symbol calls: `invoke` lets an object be called like a function, and `plus` backs `+`.
Outcome
A sealed interface, `Outcome<out T>`, for a result that is either `Ok(value)` for success or `Problem(message)` for failure. A `when` over it needs no `else` branch, and `Problem` fits any `Outcome<T>` because it is an `Outcome<Nothing>`.

P

partition
Splits a list into the items that match a test and the rest.
path parameter
A part of a route's path in braces that can match anything, such as `{code}` in `/menu/{code}`.
plugin (Ktor)
A feature installed in a Ktor server with `install`, such as `ContentNegotiation` or `StatusPages`.
port
A numbered door on a computer where a server listens, such as 8080. A server's log may show `0.0.0.0`, meaning every address of this computer.
producer/consumer
A pattern where one coroutine makes values and others use them, usually through a channel.

Q

query parameter
A name and value after `?` in an address, such as `?max=400`.

R

race condition
A wrong, run-to-run varying result caused by coroutines changing the same data at the same time, such as lost `cups++` updates.
raw string
A string between three double quotes that can hold `"` and span lines, handy for writing JSON in code.
reified
A type parameter of an inline function whose real type is available at run time, so `x is T` works.
require and check
Functions that throw if a condition is false: `require` throws `IllegalArgumentException` (bad input) and `check` throws `IllegalStateException`.
REST API
A set of endpoints named after the things they handle, such as `/menu` and `/orders/7`, that send JSON back and forth.
route
A route is code that answers one method and path. `routing { }` is the Ktor DSL where you add routes.
runBlocking
Starts a coroutine that blocks the current thread until it finishes, used in `main` and in tests.
runTest
A test helper from `kotlinx-coroutines-test` that uses virtual time: delays are skipped but the order of events is kept, so coroutine tests run fast.

S

scope function
Functions that run a lambda on one object: `let` and `also` use `it`, while `run`, `with` and `apply` use `this`. They differ in what they return.
sealed interface
An interface with a fixed set of implementations, so a `when` over it needs no `else`.
sequence
A lazy collection, made with `asSequence()`, that passes one item at a time through every step, only when a last step such as `toList()` asks.
serialization
Turning an object into text such as JSON that you can send or save. Turning it back is deserialization.
server
A program that waits for requests and answers them, like the Kettle & Crane order API.
shared mutable state
Data that several coroutines can change, which is risky without a lock.
smart cast
Kotlin treating a value as a more specific type after a check such as `is Ok`, so you can use `value` directly.
source set
A folder of source files compiled for some targets, such as `commonMain` for all and `jvmMain` for the JVM only.
star projection
`List<*>` means a list of some unknown type, whose items you read as `Any?`.
StateFlow
A hot flow that always holds one current value and skips values equal to it. `update { }` changes the value safely, even from many coroutines.
status code
A response's number saying how the request went: 200 OK (worked), 201 Created (new thing stored), 400 Bad Request (request is wrong), 404 Not Found (nothing at that path), 415 Unsupported Media Type (missing JSON Content-Type). Ktor names them in `HttpStatusCode`, such as `HttpStatusCode.NotFound`.
StatusPages
A Ktor plugin that handles exceptions in one place, such as answering 400 for every `BadRequestException`.
structured concurrency
The rule that a coroutine started inside another is its child, and a parent isn't complete until its children are. A failing child cancels its parent and siblings.
supervisor
A scope where one child's failure doesn't cancel the others, made with `supervisorScope { }` or `SupervisorJob()`.
suspend
A function marked `suspend` may pause without blocking its thread, so only coroutines or other suspend functions can call it.

T

target
A platform a Kotlin Multiplatform project builds for, such as the JVM, Android, iOS, JavaScript or WebAssembly.
testApplication
A Ktor test helper that runs your module in memory with no real port, so `client.get("/menu")` returns a response to check.
testImplementation
A Gradle dependency line meaning only the tests use this library.
type parameter
A placeholder for a type in angle brackets, such as `T` in `Shelf<T>`.
typealias
Gives a type a second name, such as `typealias Cents = Int`.

U

unit test
A small function that runs one piece of code with known input and checks the result.
upper bound
A limit on which types a type parameter allows, such as `<T : Comparable<T>>` or `<T : Priced>`.

V

variance
Which substitutions between related generic types are safe, such as `List<MenuItem>` standing in for `List<Any>`. You mark it with `out` or `in`.

W

withContext
Runs a block on another dispatcher, waits for it, returns its result, and then carries on where it was.
withTimeout
Cancels a block that runs too long. `withTimeout` throws `TimeoutCancellationException`, while `withTimeoutOrNull` returns `null` so `?:` can supply a fallback.