Kotlin by Example is a hands-on introduction to Kotlin via annotated example programs. It is inspired by Go by Example and zig-by-example: read the code, read the notes, run it yourself.
Kotlin is a concise, statically-typed language for the JVM (also Native, JS, and Wasm). It emphasizes null safety, conciseness, and seamless Java interop, letting you write expressive code that runs anywhere the JVM does and beyond.
The examples are run with the Kotlin toolchain and its kotlin command-line tool.
macOS / Linux:
curl -fsSL https://kotl.in/install.sh | sh
Windows (PowerShell):
powershell -ExecutionPolicy ByPass -c "irm 'https://kotl.in/install.ps1' | iex"
You can also sdk install kotlintoolchain via SDKMAN. Check it works with kotlin --version.
The kotlin tool runs projects, not loose .kt files. Set up one small project and reuse it for every example:
my-kotlin/
├─ module.yaml
└─ src/
└─ main.kt
module.yaml:
product: jvm/appPaste an example's code into src/main.kt, then run it from the project root:
$ kotlin run
Hello, World!
kotlin run also prints a couple of INFO compiler lines as it builds; add --log-level=warn (kotlin --log-level=warn run) to show only your program's output, as the examples below do. Pass command-line arguments after --, e.g. kotlin run -- Alice 42.
A few examples (coroutines, serialization, reflection, testing) need extra libraries. Declare them in module.yaml:
product: jvm/app
dependencies:
- org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2Each example notes which dependency it requires. See the Kotlin toolchain tutorial for more.
- Hello World
- Values
- Variables
- Basic Types & Numbers
- Type Checks & Casts
- Strings & Templates
- Null Safety
- Equality
- If & When
- Ranges & Progressions
- Loops & Labels
- Functions
- Default & Named Arguments
- Varargs
- Infix Functions
- Recursion & tailrec
- Lambdas & Higher-Order Functions
- Closures
- Classes & Constructors
- Properties & Accessors
- Inheritance & Overriding
- Abstract Classes
- Interfaces
- Visibility Modifiers
- Data Classes
- Enum Classes
- Sealed Classes & Interfaces
- Objects & Companion Objects
- Nested & Inner Classes
- Extension Functions & Properties
- Generics & Variance
- Reified Type Parameters
- Type Aliases
- Inline Value Classes
- Operator Overloading
- Annotations
- Reflection
- Scope Functions
- Destructuring Declarations
- Class Delegation
- Property Delegation
- Inline Functions
- Exceptions
- Result & runCatching
- Coroutines Basics
- Suspending Functions
- async/await & Structured Concurrency
- Dispatchers & Context
- Channels
- Flows
- Reading & Writing Files
- JSON Serialization
- Regular Expressions
- String Formatting
- Sorting & Comparators
- Date & Time
- Random
- Command-Line Arguments
- Building a Type-Safe DSL
- Testing
Released under CC BY 4.0.