Kotlin Cheatsheet — Quick Reference
A Kotlin 2.0 syntax, null safety, coroutines, and most-used standard library cheatsheet covering about 80% of everyday scenarios.
Kotlin Kotlin 2.0
JVM (kotlinc) / Multiplatform · OOP, functional, multiplatform · Static, strong typing, type inference
Recommended Learning Path
First, learn kotlinc compile/run and fun main → grasp variables, types, and control flow → understand null safety (nullable ?, safe call ?., Elvis ?:) and data class → use lambdas, extension functions, and functional collection operations → dig into classes, interfaces, and generics → handle errors with try / runCatching → write concurrency with coroutines and Flow → finally learn networking, time, regex, and Gradle build as needed. The FAQ section is worth revisiting to avoid pitfalls.
1.Hello World and Build Environment
Compile and run Kotlin programs: kotlinc toolchain, scripts, package layout, and command-line arguments.
Minimal Program
Every Kotlin program starts with a top-level fun main() as its entry point; println writes to standard output. Kotlin 2.0 supports a no-argument main.
Run and Build
kotlinc compiles source to JVM bytecode; run with java -jar. Gradle is the mainstream build tool for Kotlin projects.
Kotlin Script
.kts files can be run directly, ideal for small tools and automation. Scripts don't need a main function; top-level statements execute in order.
Package and Import
package declares the file's package; import brings in other package types. Unlike Java, unused imports don't cause errors.
Command-Line Arguments
The main's Array<String> parameter receives command-line arguments; args[0] is the first. Arguments are always strings and must be converted manually.
Output and Formatting
println outputs with a newline; print without. The string template ${} embeds expressions — the most common formatting idiom.
Exit Code
exitProcess immediately terminates the program with the given exit code; 0 means success, non-zero means failure. Don't call it in library code.
Environment Setup
IntelliJ IDEA Community Edition has built-in Kotlin support, as does Android Studio. For the command line, use kotlinc and Gradle.
2.Variables and Constants
Variable declarations, val/var, constants, type inference, destructuring, and scope.
val and var
val declares a read-only reference; var declares a mutable one. Prefer val — the compiler will suggest val when a var could be val.
Type Inference
The compiler infers the variable's type from the initializer, so explicit types can be omitted. Inferred types are equivalent to explicit ones.
Explicit Type
Explicit types improve readability and are often needed for null safety and generics. Types follow the variable name, separated by a colon.
Compile-Time Constant
const val declares a compile-time constant — only primitive types and String, and only at the top level or in a companion object.
Top-Level Variable
Variables and functions can be declared at the top level of a file, without wrapping in a class. Top-level val/var are file-level globals.
Destructuring Declaration
Destructuring splits an object into multiple variables. Pair, Triple, and data classes all support destructuring.
Type Alias
typealias gives an existing type an alias for readability. It doesn't create a new type and is fully equivalent to the original.
Scope and Block
Variable scope is determined by curly-brace blocks; inner scopes can access outer ones. Same-named variables can't be declared twice in the same scope.
3.Data Types
Numbers, characters, booleans, arrays, ranges, data classes, and type conversions.
Number Types
Kotlin provides six numeric types — Byte/Short/Int/Long/Float/Double — with suffixes L, f, u to specify the exact type.
Numeric Operations
Arithmetic, bitwise operations, and math functions. Int divided by Int yields Int — note that integer division truncates.
Char and Boolean
Char represents a single character (single quotes); Boolean has only true/false. Characters have full check and conversion methods.
Arrays
Array<T> is a reference-typed array; IntArray and similar are primitive-typed (more efficient). Array size is fixed.
Ranges
The range a..b is closed; until is open on the right. Often used with for loops and the in operator.
String Type
String is an immutable sequence of UTF-16 characters. String literals use double quotes; escapes use backslash.
data class
data class auto-generates equals/hashCode/toString/copy and destructuring — pure value objects for holding data.
Type Conversion
Kotlin doesn't implicitly convert numeric types; use explicit toXxx() methods. Small-to-large conversions can still overflow — be careful.
Unit and Nothing
Unit means no return value (like Java's void). Nothing means never returns — used for functions that always throw or are unimplemented.
4.References and Null Safety
Kotlin has no raw pointers: reference semantics, nullable types, safe call, Elvis, lateinit, and value classes.
References and Objects
Kotlin has no raw pointers; all variables are references. The JVM manages lifetimes automatically — no pointer arithmetic.
Nullable Types
Appending ? to a type makes it nullable. Nullable types can't call methods directly — null checks are required, the foundation of Kotlin's null safety.
Safe Call
?. calls a method on a non-null receiver; otherwise the whole expression is null. Safe calls can be chained.
Elvis Operator
?: returns the right side when the left is null. The right side can be an expression, an early return, or a throw.
Not-Null Assertion
!! forces a nullable type to non-null, throwing NPE when null. Avoid it; use only when you're certain the value isn't null.
lateinit Property
lateinit declares a non-null var initialized later — for dependency injection or framework callbacks. Accessing before initialization throws.
by lazy Delegation
by lazy initializes on first access and caches the result. Thread-safe; great for expensive one-shot initialization.
Copy and Equality
== compares structural equality; === compares reference identity. data class copy() does a shallow copy.
value class
value class wraps a single value and is inlined at runtime, eliminating boxing overhead — a type-safe custom wrapper.
5.Control Flow
if, when, for, while, and smart casts—expression-style control flow.
if Expression
if is an expression that can return a value to a variable. Kotlin has no ternary — if-else replaces it.
when Expression
when replaces switch, supporting values, ranges, types, and conditional branches. Expression form must have an else branch.
for Loop
for iterates over ranges, collections, arrays, and other iterables. Kotlin has no C-style three-expression for.
while Loop
while checks then executes; do-while executes at least once. Conditions must be Boolean expressions.
break and continue
break exits the loop; continue skips the current iteration. Labels with @ control jumps in nested loops.
Smart Cast
After a type check, the compiler auto-casts the type — no explicit cast needed. Null and is checks enable safe use.
Labels and Jumps
Labels marked with @ tag a loop or lambda, enabling precise jumps with break, continue, and return.
takeIf and takeUnless
takeIf returns the receiver if the predicate holds, else null; takeUnless is the opposite. Often used for chained null checks and filters.
6.Functions and Lambdas
Function declarations, lambdas, higher-order functions, extension functions, scope functions, and infix functions.
Function Declaration
fun declares a function; parameters have types, return type follows the parameter list. Use Unit for no return value.
Single-Expression Function
When a function body is a single expression, use = as shorthand to omit return and braces.
Default and Named Arguments
Parameters can have default values, omitted at the call site. Named arguments can be passed in any order for clarity.
vararg
vararg accepts any number of arguments; inside the function it's an Array. Use the spread operator * to pass an array.
Lambda Expression
A lambda is an anonymous function wrapped in braces; -> separates parameters from the body. When the last parameter is a lambda, you can use trailing-lambda syntax.
Higher-Order Function
Higher-order functions take functions as parameters or return them. Standard-library higher-order functions like map/filter are daily workhorses.
Extension Function
Extension functions add methods to existing classes without modifying them. this refers to the receiver; scope is limited to the declaration site.
Infix Function
The infix keyword lets a function be called with spaces, like an operator. Requires a member or extension function with a single parameter.
Scope Function
let/run/with/apply/also execute code in an object's context. let returns the result; apply returns the receiver.
Local Function
Local functions can be defined inside functions, capturing outer variables. Useful for organizing logic and reducing duplication.
7.Strings
String basics, templates, raw strings, methods, concatenation, formatting, and conversions.
String Basics
String is an immutable character sequence. Double-quoted literals, escape sequences, index access, and iteration.
String Template
$variable and ${expression} embed values into strings — the most common string-building idiom.
Raw String
Triple-quoted """ raw strings preserve newlines and formatting without escaping. trimIndent strips common indentation.
Common Methods
The standard library provides rich string methods: substring, replace, emptiness checks, trimming, padding.
Concatenation and StringBuilder
Use StringBuilder (or buildString) in loops to avoid creating many intermediate strings.
Formatting
The format method implements printf-style formatting with width, precision, and type placeholders.
String Conversion
Convert between strings and numbers, or to Boolean. The toXxxOrNull family returns null on failure instead of throwing.
Split and Join
split divides by delimiters into a list; joinToString joins a collection into a string. Multiple delimiters supported.
8.Collections
List, Set, Map, lazy sequences, transformations, grouping, and sorting.
List
listOf creates a read-only list; elementAt and get access by index. The default List interface is not modifiable.
Set
setOf creates a collection of unique elements. Membership checks are faster than List.
Map
mapOf creates key-value pairs; to or Pair constructs entries. Get by key; missing keys can return a default.
Mutable Collections
mutableListOf/mutableSetOf/mutableMapOf create mutable collections. The read-only view can't add.
Lazy Sequence
Sequence is lazy; chained operations execute element-by-element at the terminal operation. Avoids intermediate collections for large data.
Transform Operations
map/filter/flatMap are collection-processing workhorses, replacing hand-written loops with functional style.
Grouping and Associating
groupBy groups by condition; associate builds key-value relationships; partition splits into two.
Sorting
sorted/sortedBy return new sorted lists; sort sorts mutable lists in place. Custom comparators supported.
Collection Conversion
Convert between collections, arrays, and Maps. toList/toSet/toMap/toTypedArray.
9.Memory and Performance
JVM garbage collection, object references, boxing, allocation optimization, and performance analysis.
JVM Garbage Collection
Kotlin/JVM uses GC for automatic memory management — no manual freeing. Unreachable objects are reclaimed.
Object References
All Kotlin objects are accessed via references — no pointers. Reference types determine sharing and reachability.
inline Function
inline expands the function body at the call site, eliminating Lambda object overhead. reified generics require inline.
Allocation Optimization
Reducing object allocation is key to JVM performance. Reuse objects, avoid boxing, use primitive-typed arrays.
Primitive Boxing
Non-null primitive local variables use raw types; nullable or generic types are boxed. value class optimizes wrappers.
Performance Tuning
Measure before optimizing. Common targets: data structures, repeated computation, lazy evaluation, and algorithmic complexity.
Object Pool
Reuse objects in high-concurrency scenarios to avoid frequent allocation. Pool objects must be thread-safe and cleared before return.
Performance Profiling
Use JFR, VisualVM, etc. to analyze CPU and memory. Heap dumps locate memory leaks.
10.Object-Oriented Programming
Classes, constructors, properties, inheritance, interfaces, generics, data classes, and sealed classes.
Class Definition
class declares a class; properties can go in the primary constructor or body. Classes are final by default — not inheritable.
Constructors
The primary constructor is declared in the class header; parameters can directly become properties. init blocks run after primary construction.
Properties
Properties auto-generate getter/setter. Accessors can be customized; field refers to the backing field.
Inheritance and Overriding
An open class can be inherited; open members can be overridden. override marks an override; super accesses the parent.
Interface
Interfaces define behavior contracts; they may include default implementations and abstract members. A class can implement multiple interfaces.
Abstract Class
abstract class defines a partial implementation; abstract members must be implemented by subclasses. Unlike interfaces, abstract classes can hold state.
data class
data class auto-generates equals/hashCode/toString/copy/componentN — ideal for value objects.
Sealed Class
sealed class restricts subclasses to the same package/module; when branches can be exhaustive. Expresses limited hierarchies.
Singleton Object
object declares a singleton, lazily initialized in a thread-safe way. Only one instance exists for the entire program.
Companion Object
companion object provides class-level members, similar to Java static. Use @JvmStatic to expose them to Java.
Generics
Generics parameterize types. in/out declare variance; generic functions and type constraints are supported.
Delegation
The by keyword enables interface delegation and delegated properties. lazy/observable manage properties, simplifying composition.
11.Error Handling
try expressions, custom exceptions, runCatching, Result, require/check, and resource management.
try Expression
try is an expression; it can return a value from catch. catch matches exception types; finally always executes.
Throwing Exceptions
throw throws an exception object. Custom messages and exception chains. require/check are idiomatic for validation.
Custom Exception
Subclass Exception or RuntimeException to define custom exceptions. Can carry extra fields.
runCatching
runCatching catches exceptions and returns a Result — a functional-style alternative to try-catch.
Result Type
Result<T> wraps a success value or failure exception, supporting map/onSuccess etc. Commonly used as a return type.
Resource Management
The use extension auto-closes Closeable/AutoCloseable resources — like Java's try-with-resources.
require and check
require validates arguments; check validates state; error actively fails. They throw and print the message on failure.
Nothing and Failure
Nothing represents never returning — for unimplemented (todo) or must-fail (error) paths. The type system understands the control flow.
12.Input and Output
File reading/writing, Path API, standard I/O, JSON serialization, and file operations.
Read File
readText reads the whole file as a string; readBytes reads bytes. Specify the charset to avoid mojibake.
Write File
writeText overwrites; appendText appends; writeBytes writes bytes. The directory must exist first.
Line-by-Line Reading
readLines reads all lines; useLines is a lazy stream for big files. forEachLine is a convenient traversal.
Path API
java.nio.file.Path handles paths; Files provides read/write and directory operations. Path joining is cross-platform.
Standard Input
readln reads a line; readlnOrNull reads possibly null. Convert manually to the desired type after reading.
Standard Output
println/print write to standard output; println adds a newline. Can also write to the error stream.
JSON Serialization
kotlinx.serialization is the official serialization library; @Serializable generates codecs. Jackson is an alternative.
File Operations
Check existence, delete, rename, get size and permissions. walkTopDown recursively walks directories.
13.Common Pitfalls
The most common pitfalls in everyday Kotlin development, with BAD/GOOD examples.
Overuse of !!
!! throws NPE on null — avoid it. Use safe call, Elvis, or eager validation instead.
Smart Cast Failure
Smart casts fail on mutable or delegated properties. Re-check after assignment or capture into a local first.
== vs ===
== compares structural equality; === compares reference identity. Distinguish between objects and primitives.
Nullable Concatenation
When a nullable value is concatenated into a string template, null renders as "null". Handle null explicitly.
Template Nullable Trap
$a.b is parsed as property access a.b. Nullable object property access needs ${a?.b}.
Array Covariance Trap
Array<String> can be assigned to Array<Any>, risking ArrayStoreException at runtime. Prefer List.
lateinit Uninitialized
Accessing a lateinit property before initialization throws UninitializedPropertyAccessException. Check isInitialized first.
Scope Function Confusion
let/apply/run have different return values. Misuse returns the receiver instead of the result. Choose by purpose.
Companion Object Confusion
Companion object members aren't class-level static fields. Kotlin uses companion objects for static semantics; expose to Java with @JvmStatic.
Read-Only View Misunderstanding
The read-only List is just a view — the underlying mutable collection can still mutate. Copy when sharing mutable state.
14.Concurrency and Coroutines
Threads, coroutines, async/await, Channel, Flow, mutex locks, and timeout control.
Thread Basics
Thread and thread{} create threads. join waits for completion. Synchronize when sharing mutable state in concurrency.
Coroutine Basics
launch starts a lightweight coroutine; delay suspends without occupying a thread. runBlocking blocks until coroutines complete.
async and await
async runs concurrently and returns Deferred; await gets the result. awaitAll waits for many tasks.
withContext
withContext switches dispatchers for blocking tasks. Use Dispatchers.IO for I/O; Default for compute.
Channel
Channel transports data between coroutines; send/receive are suspending functions. Supports buffering and closing.
Flow
Flow is an asynchronous cold stream — it runs at collection time. Supports map/filter operators and backpressure.
Mutex and Synchronization
AtomicInteger provides lock-free counters. Use Mutex inside coroutines to guard critical sections; synchronized for threads.
Timeout and Cancellation
withTimeout limits coroutine execution time. job.cancel is cooperative cancellation — check isActive.
15.Network Programming
HTTP requests, Ktor Client, JSON parsing, TCP Sockets, HTTP servers, and WebSocket.
Simple URL Request
URL.readText is a quick GET. openConnection lets you configure timeouts. Good for small lightweight responses.
JDK HttpClient
JDK 11+ has built-in HttpClient for HTTP requests. Supports async sendAsync and response-body conversion.
Ktor Client
Ktor Client is a cross-platform HTTP library supporting coroutines and multiple engines. Good for network-heavy tasks.
Parse Response JSON
After getting a response via HttpClient, use kotlinx.serialization to deserialize JSON into a data class.
TCP Socket
ServerSocket listens on a port; accept accepts a connection. Socket reads/writes byte streams. Remember to close resources.
HTTP Server
JDK's built-in HttpServer creates a lightweight HTTP service. createContext registers route handlers.
REST Design Principles
REST expresses operations with resources and HTTP methods. data class describes request/response; status codes carry clear semantics.
WebSocket
OkHttp provides a WebSocket client with onOpen/onMessage callbacks for bidirectional messaging.
16.Date and Time
Instant, LocalDate, formatting, parsing, Duration, Period, and zoned date-times.
Current Timestamp
Instant.now records the current instant. currentTimeMillis gets milliseconds; nanoTime measures intervals.
LocalDate
LocalDate represents year-month-day; create with of/now. Add/subtract days, compare, and access components.
LocalDateTime
LocalDateTime has date and time. withHour adjusts a field; plusHours adds/subtracts hours.
Formatting Output
DateTimeFormatter.ofPattern defines a custom format. yyyy-MM-dd HH:mm:ss is a common pattern.
Parse Date
LocalDate.parse parses a string. Custom formats need a DateTimeFormatter. Failures throw exceptions.
Duration
Duration is a nanosecond-based time amount; between computes the diff. Ideal for measuring elapsed time.
Period
Period is a year/month/day amount; between computes age. ofWeeks/ofDays construct periods.
Zoned Date-Time
ZonedDateTime carries a time zone. withZoneSameInstant switches zones. Store in UTC; display in local.
17.Processes and System
Command-line arguments, environment variables, ProcessBuilder for external commands, system info, and shutdown hooks.
Arguments and Environment
The main args receives command-line arguments. System.getenv reads env vars; getProperty reads system properties.
ProcessBuilder
ProcessBuilder runs external commands; directory sets the working directory. redirectErrorStream merges error streams.
Exit Code
waitFor blocks waiting for the child process. Exit code 0 means success. exitProcess sets the current process's exit code.
Capture Child Process Output
Read inputStream to capture child-process output. Use waitFor with timeout to avoid hangs; destroyForcibly force-kills.
System Information
Read JVM and OS properties; Runtime exposes memory. Used for logging and diagnostics.
Shutdown Hook
addShutdownHook registers a task that runs when the JVM exits. Used for cleanup and state persistence.
Real-Time Output Reading
Read the child-process output stream line by line to handle progress in real time. useLines auto-closes the stream.
Terminate Process
destroy is a graceful termination; destroyForcibly is a force kill. Force-terminate when timeout elapses.
18.Regular Expressions
Regex basics, match search, capture groups, replace/split, common patterns, and flag options.
Regex Basics
Regex creates a regex object. matches for full match; containsMatchIn to check containment; matchEntire for whole-string match.
Literal and Options
Regex.escape escapes special characters. IGNORE_CASE ignores case; MULTILINE is multiline mode.
Find Match
find returns the first match; findAll returns all matches. MatchResult exposes value, groups, and range.
Capture Groups
Parentheses define capture groups. groupValues is indexed; named groups use groups["name"].
Regex Replace
replace replaces all matches; replaceFirst only the first. The replacement closure can access capture groups.
Regex Split
split(Regex) splits a string with a regex. More flexible than string splitting; supports multiple delimiters.
Common Regex
Common regex templates for email, phone, IPv4, Chinese chars, and URL. Adjust boundaries as needed.
Flag Options
RegexOption constants control matching behavior. Inline flags (?i)(?m)(?s) can appear inside the pattern.
19.Build and Dependencies
Gradle Kotlin DSL, plugins, dependencies, testing, coroutines, and serialization library configuration.
Gradle Basics
build.gradle.kts uses Kotlin DSL to configure the build. mainClass specifies the run entry point.
Kotlin Plugin
kotlin("jvm") declares a JVM project. jvmToolchain specifies the JDK version. Wrapper pins Gradle.
Dependency Configuration
implementation/testImplementation/compileOnly etc. control dependency scope.
Run and Distribution
The application plugin provides run/installDist tasks. run --args passes CLI arguments.
Testing
kotlin.test provides assertions. testImplementation brings in test deps. The test task runs all tests.
Coroutine Dependencies
kotlinx-coroutines-core provides coroutine core. Android/Swing variants provide matching main-thread dispatchers.
Serialization Dependencies
The kotlin plugin.serialization plugin plus kotlinx-serialization-json enables JSON encoding/decoding.
Packaging and Publishing
The distribution plugin produces distributable archives. publishToMavenLocal publishes to the local Maven repo.
Official Links
Direct links to the official docs and resources.
About this Cheatsheet
This page is a self-contained Kotlin 2.0 cheatsheet, covering about 80% of common usage of the language core and the most-used standard library in real projects. It leans on modern idioms: null safety (nullable types ?, safe call ?., Elvis ?:), data class and sealed class, scope functions, extension functions, and the coroutine + Flow async concurrency model. For authoritative references, see the official Kotlin documentation and Kotlin in Action. 19 sections each focus on one topic — from your first program through coroutines, null safety, and common pitfalls. Each section is split into 8–14 example-driven subsections (5–20 lines each) for about 160 topics. Code snippets are intentionally short and self-explanatory; comments are in Simplified Chinese. All processing happens in the browser — no uploads, no tracking. This page is part of GuruToolkit's free developer tool collection; the snippets are free to use with no warranty.
Version 2.1.0