Programming Languages
Learn Kotlin from syntax and null safety to coroutines, multiplatform and server-side frameworks.
A path from first Kotlin program to production use. It covers syntax, types, null safety, collections, functions and classes, then coroutines, the standard and official libraries, build tooling, and the platforms Kotlin targets: JVM, Android, native, web and multiplatform. Each subject links the official documentation.
The subjects follow the roadmap.sh Kotlin roadmap.
Kotlin is a statically typed language from JetBrains that compiles to JVM bytecode, JavaScript, WebAssembly and native binaries. It is concise, null-safe by design and fully interoperable with Java, which made it Google's preferred language for Android and a strong choice for backends.
Less boilerplate than Java (data classes, type inference, properties), null safety enforced by the compiler, coroutines for async code and one language across Android, server, web and native targets.
Announced by JetBrains in 2011, 1.0 shipped in 2016, Google endorsed it for Android in 2017 and declared Android Kotlin-first in 2019. Kotlin 2.0 (2024) brought the new K2 compiler.
Kotlin calls any Java library directly and Java can call Kotlin, so you can migrate a codebase file by file. Platform types from Java carry unknown nullability, so add checks at the boundary.
Install a JDK and IntelliJ IDEA (which bundles the Kotlin plugin), then create a Gradle project; the Kotlin Playground lets you try code in the browser with no setup.
Kotlin source files declare a package, may hold any number of top-level functions, classes and properties, and need not match a class name. Packages and imports control naming; the entry point is a top-level main.
Execution starts at a top-level fun main(), optionally fun main(args: Array<String>) to read command-line arguments. No enclosing class is needed.
// for single lines and /* */ for blocks; unlike Java, block comments can nest. /** */ comments are KDoc, picked up by documentation tools.
A package line at the top of a file namespaces everything in it. Directory layout is a convention, not a rule, though the coding conventions recommend matching it.
import brings in single names or a whole package with *; as renames on import to resolve clashes. Top-level functions and properties are imported just like classes.
Variables are declared with val or var, with a type annotation only when the compiler cannot infer it. Values are printed with standard library functions and formatted with string templates rather than concatenation.
val is a read-only reference assigned once, var can be reassigned. Default to val; note that a val pointing to a mutable list can still have its contents changed.
The compiler works out types from initialisers and expressions, so val count = 3 is an Int. Declare types explicitly on public APIs to keep them stable and readable.
Console output goes through the standard library's print functions; for anything beyond debugging, use a logging library rather than writing to stdout.
print writes its argument as a string, println adds a line break. Both call toString() on the value; readln() is the matching input function.
Embed values with "$name" or expressions with "${user.age + 1}". Raw strings in triple quotes keep newlines and backslashes; trimIndent() tidies their indentation.
Everything is an object in the language, but the compiler maps numbers, characters and booleans to JVM primitives where possible. Nullable variants (Int?) are boxed. There are no implicit widening conversions — call toLong() and friends explicitly.
Byte, Short, Int and Long are 8 to 64 bits; an integer literal is Int unless it exceeds the range or ends in L. Underscores like 1_000_000 aid readability.
UByte, UShort, UInt and ULong with a u suffix on literals. Useful for bytes from protocols and hashes; they are implemented as inline classes over the signed types.
Double is the default for decimal literals and Float needs an f suffix. Both follow IEEE 754, so use BigDecimal for money.
Boolean holds true or false and supports &&, || (both short-circuit) and !. A Boolean? can also be null, so if (flag == true) is a common idiom.
Char is a 16-bit UTF-16 code unit written in single quotes. It is not a number: convert with .code and Char(code), and use digitToInt() for digits.
String is immutable; indexing gives a Char, and functions like split, substringAfter, padStart and buildString cover most manipulation. Compare with ==, which checks content.
Array<T> is fixed-size and mutable; primitive arrays such as IntArray avoid boxing. Prefer lists in most code and reach for arrays for performance or Java APIs.
is checks a type and smart-casts the variable inside that branch; as casts explicitly and throws ClassCastException on a mismatch.
The type system separates types that can hold null from those that cannot, so most null-pointer errors become compile errors. Nulls still enter through Java calls, !! and late initialisation, which is where to stay alert.
String can never be null; String? can, and the compiler will not let you call members on it until you have handled the null case.
?. calls only when non-null, ?: (Elvis) supplies a fallback or return/throw, and !! asserts non-null and throws if wrong — treat every !! as a code smell.
as? returns null instead of throwing when the cast fails, which pairs naturally with Elvis: (x as? String) ?: return.
Branching constructs are expressions that return values, so there is no ternary operator — val max = if (a > b) a else b does the job. Combined with smart casts this removes a lot of temporary variables.
Works as a statement or an expression; when used as an expression the else branch is required and the last expression of each block is the value.
A powerful switch replacement matching values, ranges (in 1..9), types (is String) or arbitrary conditions. Used as an expression over a sealed type or enum, it must be exhaustive.
Kotlin has for over anything with an iterator, plus while and do-while. Counting loops are written with ranges and progressions rather than C-style headers, and labels let you break out of nested loops.
for (item in list), for (i in 0 until n), for ((i, v) in list.withIndex()) and destructuring over maps with for ((k, v) in map).
while checks the condition first; do { } while (cond) runs the body at least once and can see variables declared inside the body in its condition.
break exits the nearest loop and continue skips to its next iteration. Inside forEach lambdas they are not allowed; use a labelled return@forEach or a plain loop.
Mark a loop with outer@ and write break@outer or continue@outer to target it from a nested loop. Labels also qualify return inside lambdas.
1..10 is inclusive, 1..<10 (or until) excludes the end. Ranges support in checks for any comparable type, such as c in 'a'..'z'.
Integer ranges are progressions with a step: 10 downTo 1, 0..100 step 5. They are iterable, and reversed() flips direction.
Kotlin has no checked exceptions: nothing forces you to catch or declare them, so document what can fail. try is an expression, and for expected failures Result or sealed result types are often clearer than throwing.
throw IllegalStateException("…"); require, check and error are shorthand for argument, state and unconditional failures. throw has type Nothing, so it works inside Elvis expressions.
try { } catch (e: IOException) { } finally { }, usable as an expression. runCatching { } wraps the outcome in a Result; beware it also swallows coroutine cancellation.
The standard library provides lists, sets and maps, each with a read-only interface and a mutable subtype, all backed by JVM collections on that platform. Learning which type to expose and when to switch to a sequence is the core skill.
Ordered, index-accessible and allowing duplicates. Build with listOf, mutableListOf or buildList; list-specific helpers include getOrNull, binarySearch and subList.
Unique elements; setOf keeps insertion order (a LinkedHashSet). Set algebra uses union, intersect and subtract.
Key-value pairs built with mapOf("a" to 1). Read with map[key] (nullable) or getValue (throws); getOrPut, filterKeys and mapValues cover common transformations.
List has no add, but it is a read-only view, not an immutable copy: a MutableList behind it can still change. Expose read-only types and keep mutation private.
Any Iterable gives an iterator() with hasNext and next; MutableIterator adds remove. Usually hidden behind for loops and forEach.
Lazily evaluated chains (asSequence(), generateSequence, sequence { yield(x) }) that process one element at a time through all steps. Worth it for long pipelines or infinite streams, not tiny lists.
The standard library ships hundreds of extension functions on collections. Each returns a new collection rather than modifying the original, unless its name says otherwise (sort versus sorted).
map, mapNotNull, flatMap, zip, associate and joinToString turn one collection into another shape.
filter, filterNot, filterIsInstance<T>() and partition keep elements by predicate; any, all and none test them.
list + item and list - other return new collections; on mutable collections += adds in place, which can be ambiguous with a var holding a read-only list.
groupBy { it.category } builds a Map<K, List<T>>; groupingBy with eachCount or fold aggregates groups without building intermediate lists.
take, drop, takeWhile, slice, chunked and windowed extract sub-ranges or split collections into pieces.
first, last, elementAt, find, single and their OrNull variants; prefer the nullable variants when absence is a normal case.
sorted, sortedBy, sortedWith(compareBy({ it.a }, { it.b })) and reversed; mutable lists also have in-place sort and shuffle.
sum, sumOf, count, maxByOrNull, average, plus fold and reduce for custom accumulations.
Functions are declared with fun, can live at top level, inside classes or inside other functions, and may have a single-expression body (fun twice(x: Int) = x * 2). Default and named arguments replace most overloads.
Parameters are read-only and typed; they can have defaults and be passed by name, so connect(timeout = 5) skips everything else. @JvmOverloads exposes defaults to Java.
Mark one parameter vararg to accept any number of arguments as an array; pass an existing array with the spread operator, *items.
Block bodies need an explicit return with a declared type unless they return Unit. Inside a lambda a bare return exits the enclosing function only when the lambda is inlined; otherwise use return@label.
Functions declared inside another function can read its local variables, a tidy way to share a helper without widening its visibility.
Functions defined inside a class or object and called on an instance with dot notation. They can be open for overriding, and a member always wins over an extension with the same signature.
A function marked tailrec whose recursive call is the last operation is compiled into a loop, so it cannot overflow the stack. The compiler warns if the call is not in tail position.
Add functions to existing types without inheriting: fun String.slugify(): String. They are resolved statically from the declared type, so they do not override members or dispatch virtually.
Functions are values with types like (Int, Int) -> Int or suspend () -> Unit. That makes lambdas, callbacks and DSLs first-class; inline functions remove the allocation cost of passing them.
{ a, b -> a + b }; a single parameter is available as it, and a trailing lambda can move outside the parentheses: list.filter { it > 0 }.
Functions that take or return other functions, like map or a retry(times) { … } helper. Mark them inline to avoid lambda objects and allow non-local returns.
fun(x: Int): Int { return x * 2 } — like a lambda but with an explicit return type, and a return inside exits only the anonymous function itself.
Classes are declared with class, are final by default and usually define their constructor and properties in one header line. Getters, setters, equals for data classes and delegation are generated or declared concisely.
Call the constructor like a function — there is no new keyword: val user = User("Ana", 30).
A class body can hold constructors and init blocks, properties, functions, nested and inner classes, and object declarations including a companion object.
The primary constructor sits in the header and can declare properties directly with val/var; init blocks run its logic. Secondary constructors must delegate to the primary with this(…).
Fields with generated accessors; customise with get() and set(value) using field as the backing field. lateinit var and const val cover late and compile-time values.
Behaviour on a class is written as member functions that read and change its properties; Kotlin calls them functions rather than methods but they compile to ordinary JVM methods.
Every class extends Any. Classes and members are final unless marked open; subclasses use : Base() and override. Prefer composition and interface delegation (by) when possible.
public (default), private, protected and internal, which means visible within the same module. Use internal to hide implementation across a library boundary.
val x by lazy { }, Delegates.observable and by map hand a property's get/set to another object. Write your own with getValue/setValue operators.
A nested class has no reference to its outer instance, unlike Java's default. Mark it inner to access outer members, at the cost of holding that reference.
object Registry { } is a lazily created singleton; companion object holds factory functions and constants; object : Listener { } creates an anonymous instance.
Specialised class kinds cover most modelling needs: data holders, closed hierarchies, enumerations, zero-cost wrappers and generic containers. Picking the right one removes boilerplate and lets the compiler check exhaustiveness.
An abstract class cannot be instantiated and may declare abstract members subclasses must implement, while also holding state and concrete code.
Interfaces can declare abstract and default-implemented members and abstract properties, but no state. fun interface allows SAM conversion from a lambda.
data class generates equals, hashCode, toString, copy and componentN from primary-constructor properties. Keep them immutable with val.
A closed hierarchy whose subclasses are all known at compile time, so when over it needs no else. Ideal for UI states, results and protocol messages.
A fixed set of constants that can carry properties and functions; entries lists them and valueOf parses a name.
@JvmInline value class UserId(val raw: String) adds type safety around a single value while usually compiling to the raw value, with no allocation.
typealias Handler = (Event) -> Unit gives an existing type a shorter name. It does not create a new type; use a value class for that.
class Box<T>(val item: T), with declaration-site variance (out T, in T), upper bounds (T : Comparable<T>) and reified type parameters in inline functions.
A coroutine is a computation that can pause at a suspend point and later pick up where it left off, so async code reads top to bottom with no callbacks. The compiler supplies suspend; kotlinx.coroutines adds builders, dispatchers, structured concurrency and Flow. Thousands can share a handful of threads.
A suspend fun can pause without blocking its thread and resume later; it can only be called from another suspend function or a coroutine. Under the hood it compiles to a state machine.
launch starts a fire-and-forget job, async returns a Deferred to await, runBlocking bridges blocking code (tests, main), and coroutineScope groups child work.
A coroutine's context combines a Job (lifecycle and parent-child links), a dispatcher (Dispatchers.Default, IO, Main) and optional exception handler. Cancellation is cooperative and propagates through the hierarchy.
Flow<T> is a cold asynchronous stream: built with flow { emit(x) }, transformed with operators and collected with collect. StateFlow and SharedFlow are the hot variants for state and events.
Never use GlobalScope; tie work to a lifecycle scope. Inject dispatchers for testability, do not swallow CancellationException, and make suspend functions main-safe.
kotlin-stdlib supplies collections, text, ranges, scope functions (let, apply, also, run, with), I/O helpers and more on every platform. Reading its API reference is one of the fastest ways to write idiomatic code.
Every file implicitly imports kotlin.*, kotlin.collections.*, kotlin.text.*, kotlin.ranges.* and a few more, plus java.lang.* and kotlin.jvm.* on the JVM.
APIs marked with a @RequiresOptIn annotation (experimental or delicate ones) need callers to acknowledge them with @OptIn(...) or a compiler flag.
Official kotlinx libraries extend the standard library with features that evolve faster: serialization, coroutines, I/O, date-time and more. Most are multiplatform, so they work in shared KMP code.
kotlinx.serialization uses a compiler plugin and @Serializable to generate reflection-free encoders for JSON, CBOR, Protobuf and more.
kotlinx-io offers multiplatform buffers, sources and sinks; on the JVM the stdlib's kotlin.io extensions over java.io remain the everyday tool.
kotlinx-datetime provides LocalDate, LocalDateTime and TimeZone across platforms; on the JVM alone, java.time works fine too.
Kotlin stores language-level details (nullability, properties, default arguments) in a @Metadata annotation in class files. The kotlin-metadata-jvm library reads and writes it for tooling.
kotlin.test gives multiplatform @Test annotations and assertions like assertEquals and assertFailsWith, running on JUnit on the JVM.
Kotlin code is documented with KDoc comments, and Dokka turns them into a browsable reference site. Public library APIs should document parameters, return values and thrown exceptions.
Kotlin projects are built mostly with Gradle (and its Kotlin DSL), sometimes Maven. The build tool runs the compiler, resolves dependencies and applies compiler plugins like serialization or all-open.
The default build tool for Kotlin and Android. Write build.gradle.kts in the Kotlin DSL, keep versions in a libs.versions.toml catalog and use the Gradle wrapper.
kotlin("jvm"), kotlin("multiplatform"), kotlin("plugin.serialization") and kotlin("plugin.spring") configure compilation targets and compiler plugins.
The kotlin-maven-plugin compiles Kotlin in Maven builds; compile Kotlin before Java when both live in one module.
An experimental API that lets build systems drive the Kotlin compiler through a stable interface instead of internal entry points, used to integrate Kotlin into tools beyond Gradle and Maven.
Any CI system that runs Gradle can build Kotlin: cache the Gradle home, run ./gradlew check on each push and publish artifacts on tags. GitHub Actions has an official Gradle setup action.
JetBrains' CI server, whose pipelines can be configured as code in a Kotlin DSL — a natural fit for teams already in the JetBrains ecosystem.
Kotlin tooling is strongest in JetBrains IDEs, which provide refactoring, inspections, a debugger aware of coroutines and Java-to-Kotlin conversion. A Language Server for other editors exists but is less mature.
The reference Kotlin IDE, made by Kotlin's creators; the free edition covers JVM and multiplatform work, and it converts Java files to Kotlin with one action.
Google's IntelliJ-based IDE for Android with emulators, layout and Compose previews, profilers and the Android Gradle plugin built in.
On the JVM, Kotlin adds concise extension functions on java.io.File, streams and readers, and works with java.nio.file.Path too. Always close resources with use { }, Kotlin's try-with-resources.
File("out.txt").createNewFile(), mkdirs() for directories, or Path.createFile() and createDirectories() from kotlin.io.path.
readText, readLines, writeText and appendText for small files; useLines { } streams large files line by line without loading them whole.
bufferedReader() and bufferedWriter() wrap streams so reads and writes happen in chunks, which matters for large files and network streams; close them with use.
KMP shares business logic across Android, iOS, desktop, web and server while keeping native UI where wanted. Common code lives in commonMain; platform specifics use expect/actual declarations.
JetBrains' declarative UI framework based on Jetpack Compose, letting one UI codebase run on Android, iOS, desktop and web.
Kotlin/Native generates bindings from C headers with the cinterop tool, so you can call C libraries and work with pointers via CPointer and memScoped.
Kotlin/Native exports a framework that Swift and Objective-C call directly; know how nullability, generics, suspend functions and sealed classes map across.
Kotlin's main target is the JVM, and Java and Kotlin files coexist in the same module. Knowing how each side sees the other avoids surprises with nullability, statics and default arguments.
Getters and setters appear as properties, Java types become platform types (String!), and SAM interfaces accept lambdas. Annotate Java code with nullability annotations to get real types.
Top-level functions land in FileNameKt classes, and annotations like @JvmStatic, @JvmField, @JvmOverloads and @JvmName shape what Java sees.
Compiles Kotlin to native binaries via LLVM, with no JVM, for iOS, macOS, Linux, Windows and embedded targets. It powers the iOS side of Kotlin Multiplatform.
Compiles Kotlin to WebAssembly with garbage-collection support, for fast web apps (including Compose Multiplatform for web) and WASI runtimes. It is newer than the other targets, so check its current stability level.
Transpiles Kotlin to JavaScript for browsers and Node.js, with npm dependency support and TypeScript declaration generation, useful for sharing logic with a web front end.
.main.kts scripts run Kotlin without a project, pulling dependencies with @file:DependsOn. Gradle's .gradle.kts build files are the most widespread example of Kotlin scripting.
Kotlin runs on the server with the full JVM ecosystem plus coroutines for high-concurrency I/O. Choose between Kotlin-first frameworks like Ktor and established Java frameworks with first-class Kotlin support.
JetBrains' lightweight, coroutine-based framework for HTTP servers and clients, configured through plugins and a routing DSL.
Spring Framework supports Kotlin directly: null-safe APIs, bean definition DSLs, coroutine-based WebFlux handlers and extension functions.
Auto-configured Spring apps; start.spring.io generates Kotlin projects with the plugin.spring and plugin.jpa compiler plugins already applied.
A Kubernetes-oriented Java framework with fast startup and native-image support; its Kotlin extension adds Kotlin-friendly Panache and coroutine support.
An event-driven, non-blocking toolkit for reactive apps on the JVM, with Kotlin coroutine integration so handlers can be written as suspend functions.
The platform APIs and tools for building Android apps, where Kotlin is the recommended language. Modern apps combine the SDK with Jetpack libraries and Compose for UI.
Google's suite of libraries — Compose, ViewModel, Room, Navigation, WorkManager — that handle lifecycles and boilerplate consistently across Android versions.
Kotlin brings static types and JVM performance to data work through notebooks, a typed DataFrame library and plotting tools, without leaving the language your services are written in.
Interactive notebooks inside IntelliJ IDEA for exploring data, prototyping and documenting with code, output and charts in one file.
A typed, tabular data library that reads CSV, JSON and SQL and generates column accessors from the data schema.
A Kotlin plotting library with a declarative DSL for charts, designed to work smoothly with DataFrame inside notebooks.
Kotlin is accepted on major judges like Codeforces. Concise collections, readln() and fast IntArray code make it a pleasant contest language; watch boxing and slow input on large tests.
Kotlin services can call LLMs, run retrieval pipelines and host agents on the JVM, using Kotlin-native frameworks or Spring AI and LangChain4j.
JetBrains' open-source Kotlin framework for building AI agents, with tool calling, multi-step strategies and support for several LLM providers.