Kotlin code snippets with use cases
29 ready-made code building blocks, sorted by topic.
Control flow
- if / when – React differently, e.g. compute grades or price tiers.
- for Loops – Process every element of a list or repeat n times.
- when with Types – Handle values of different types (JSON, events, messages) differently.
Functions
- Function with Default Value – Bundle recurring logic, e.g. greeting texts or calculations.
- Extension Functions – Add your own helper functions to existing types (String, List).
- Scope Functions – Configure objects, process nullable values, and slip in debug output.
- Lambdas and Higher-Order Functions – Pass behavior as a parameter, e.g. callbacks, sorting, or filtering logic.
Data structures
- Working with Lists – Manage collections of values: add, sort, filter.
- Map (Dictionary) – Store mappings, e.g. configurations or counters per key.
- groupBy and partition – Group or split records, e.g. users per city.
- Lazy Sequences – Process large or infinite amounts of data without creating intermediate lists.
- Sorting by Multiple Criteria – Order records, e.g. users by age descending, then by name.
OOP
- Class with Inheritance – Bundle data and behavior, e.g. users, products, game characters.
- Data Class with copy – Data objects (DTOs, configurations, results) without boilerplate.
- object and companion object – Singletons (logger, configuration) and factory functions instead of static members.
More snippets
- Hello World – A first test of whether the compiler or playground works.
- Variables and Types – Store values; protect immutable values with val.
- try / catch / finally – Guard user input or network access without the program crashing.
- runCatching and require – Handle failing calls (parsing, network) without cascades of try/catch.
- Read and Write a File – Save and load logs, configurations, or text data.
- Read Large Files Line by Line – Analyze log files without loading everything into memory.
- Null Safety: ?. and ?: – Handle missing values (inputs, API fields) without a NullPointerException.
- Sealed Result with when – Model success and failure as types instead of throwing exceptions.
- Raw Strings & trimIndent – Write multi-line texts, paths, or regular expressions without escaping.
- Counting Words – Text analysis, e.g. the most frequent words in a document.
- Coroutines: async and await – Start several independent queries (price, discount) in parallel and combine them.
- Flow – Process data streams (sensors, live updates, database changes) asynchronously.
- Delegated Properties: lazy and observable – Compute expensive values only when needed or react to value changes.
- inline and reified – Type-dependent helper functions (filtering by type, JSON parsing) with type information…