liminfo

Kotlin Reference

Free reference guide: Kotlin Reference

40 results

About Kotlin Reference

The Kotlin Reference is a complete, searchable guide to the Kotlin programming language, organized across eight categories that cover everything from basic syntax to advanced Kotlin-specific features. The Basics category covers val/var variable declarations, fun function definitions with single-expression shorthand, when expressions with type checks and range matching, if as expression, for/while loops with ranges and downTo/step, string templates with ${} interpolation, type aliases, destructuring declarations, try as expression, and generics with variance. The Classes category covers data class with copy() and destructuring, primary constructors with init blocks, open/sealed class hierarchies, object and companion object for singletons, interfaces with default implementations, and enum class with properties. The Functions category covers lambda expressions, scope functions (let, run, with, apply, also), and inline/infix functions. The Collections category covers immutable and mutable listOf/setOf/mapOf, filter/map/reduce transformations, groupBy/associateWith, flatMap/zip, and lazy sequences. The Coroutines category covers suspend functions, launch and async builders with runBlocking, Flow for async streams, coroutineScope for structured concurrency, and Channel for communication. The Null Safety category covers safe call (?.), Elvis operator (?:), non-null assertion (!!), let with null checks, safe cast (as?), and lateinit/lazy initialization. The Extensions category covers extension functions and properties on any type, and operator overloading. The DSL category covers buildString/buildList DSL builders, delegated properties with Delegates.observable, and annotations.

Kotlin is the primary programming language for Android development and is widely adopted for server-side development with frameworks like Spring Boot, Ktor, and Quarkus. Its concise syntax, null safety type system, and first-class coroutine support make it a significant productivity improvement over Java for both Android and JVM backend developers. This reference is built for developers transitioning from Java to Kotlin, Android engineers learning Kotlin-specific idioms, and backend developers exploring Kotlin coroutines and functional collection APIs.

The reference mirrors the eight conceptual layers of Kotlin development: the basic syntax layer you use every day, the object-oriented class system, the functional programming features, the powerful collection DSL, the coroutine concurrency model, the null safety type system, the extension-based API design pattern, and the DSL/metaprogramming capabilities. Each entry includes a focused code example showing idiomatic Kotlin so you can learn the language's conventions alongside the syntax.

Key Features

  • Basic syntax: val/var declarations, fun with single-expression body, when expression with type matching, if as expression, ranges (1..5, downTo, step), and string templates
  • Class system: data class with copy() and auto-generated equals/hashCode, sealed class for exhaustive when, open class for inheritance, object for singletons, companion object, interface with default implementations, enum class with constructor parameters
  • Functional features: lambda syntax, trailing lambda convention, and all five scope functions (let, run, with, apply, also) with their receiver and return value differences
  • Collection API: immutable vs mutable collections, filter/map/reduce, groupBy for key-based grouping, associateWith for Map creation, flatMap/zip, and lazy sequences for performance
  • Coroutines: suspend function basics, launch (fire-and-forget) vs async/await (result-bearing), Flow for reactive streams with filter/collect, coroutineScope for structured concurrency, and Channel for producer-consumer communication
  • Null safety: safe call (?.) chaining, Elvis operator (?:) for defaults, non-null assertion (!!), let for null-conditional execution, as? for safe casting, and lateinit/lazy for deferred initialization
  • Extension functions and properties on String, List, and custom types, plus operator overloading with the operator modifier for natural syntax
  • DSL patterns: buildString/buildList builder functions, Delegates.observable for reactive properties, require/check precondition functions, and @JvmStatic/@Deprecated annotations

Frequently Asked Questions

What is the difference between val and var in Kotlin?

val declares an immutable (read-only) reference — once assigned, you cannot reassign it, similar to Java's final. var declares a mutable reference that can be reassigned. Note that val does not make the object itself immutable: a val list can still have elements added if it is a MutableList. Prefer val over var to write safer, more predictable code.

What is a data class in Kotlin and when should I use it?

A data class automatically generates equals(), hashCode(), toString(), copy(), and componentN() functions based on the primary constructor parameters. Use data class for immutable value objects like DTOs, domain model records, and configuration objects where equality is based on content rather than identity. The copy() function lets you create modified copies with only the changed fields.

What is the difference between launch and async in Kotlin coroutines?

launch starts a coroutine for side effects and returns a Job — you call job.cancel() or job.join() on it. async starts a coroutine that computes a result and returns a Deferred<T> — you call deferred.await() to get the result when it is ready. Use launch when you do not need a return value, async when you want concurrent computation and need the result.

What is the difference between let, apply, run, with, and also scope functions?

let: receiver is it, returns lambda result — use for null checks and transformations. run: receiver is this, returns lambda result — use for object configuration and computation. with: receiver is this (passed as argument, not extension), returns lambda result. apply: receiver is this, returns the receiver itself — use for object configuration/builder pattern. also: receiver is it, returns the receiver itself — use for side effects (logging) without breaking chains.

How does Kotlin null safety work?

In Kotlin, types are non-nullable by default. `String` cannot be null; `String?` can be null. The compiler enforces null safety at compile time. Use the safe call operator (?.) to call a method on a nullable without an NPE: `name?.length` returns null instead of throwing. Use the Elvis operator (?:) for a default value: `name?.length ?: 0`. Use !! only when you are certain the value is non-null — it throws NPE if null.

What are Kotlin extension functions and how do they work?

Extension functions let you add methods to existing classes without inheriting from them or using decorators. Define them as `fun ClassName.newMethod() { ... }`. They are syntactic sugar: the compiler converts them to static functions that take the receiver as the first parameter. Extension functions can be defined on any type including String, List, and third-party classes. They do not actually modify the class — they are resolved statically at the call site.

What is a sealed class in Kotlin and why is it useful?

A sealed class restricts its subclasses to be defined in the same file (or package in Kotlin 1.5+). This makes it ideal for representing restricted type hierarchies like Result (Success/Error), UI states (Loading/Success/Error), or network responses. When you use a sealed class in a when expression, the compiler can verify that all subclasses are handled, eliminating the need for an else branch and preventing runtime errors from unhandled cases.

What is Kotlin Flow and how is it different from a suspend function?

A suspend function returns a single value when it completes. Flow is a cold asynchronous stream that can emit multiple values over time, similar to RxJava Observable but built on Kotlin coroutines. Create a Flow with the flow { } builder using emit() to produce values. Collect values with collect() in a coroutine. Flows are cold — they do not start producing values until collected. Use Flow for UI state streams, database change notifications, and event buses in Android development.