Kotlin Examples
Every example includes runnable code and expected output. Filter by topic or difficulty.
46 examples
Hello World
The simplest Kotlin program.
Variables - val and var
Declare read-only and mutable variables.
Data Types
Common Kotlin data types in one example.
String Templates
Embed variables inside strings using $.
Arithmetic Operators
Basic math operations in Kotlin.
If / Else
Conditional logic with if and else.
When Expression
Pattern matching with when.
For Loop with Range
Iterate over a range of numbers.
While Loop
Loop while a condition is true.
Basic Function
Define and call a simple function.
Function with Return Value
Return a value from a function.
Default Arguments
Use default values for function parameters.
List Example
Create and access an immutable list.
Mutable List
Add and remove items from a list.
Map Example
Store key-value pairs in a map.
filter and map
Filter and transform a list.
Class Example
Define a class with properties.
Primary Constructor
Pass data into a class via its constructor.
Inheritance
Extend a class and override a function.
Data Class
Automatic toString, equals, and copy.
Nullable Variable
Declare variables that can hold null.
Safe Call Operator
Access properties of nullable values safely.
Elvis Operator
Provide a fallback when a value is null.
Smart Cast
Automatically cast after a type check.
Lambda Expression
Use a lambda to transform a list.
Higher-Order Function
Pass a function as a parameter.
Extension Function
Add functions to existing types.
apply Scope Function
Configure an object using apply.
try catch finally
Handle runtime errors gracefully.
Generic Class
Create a class that works with any type.
Destructuring Declarations
Unpack data class properties into variables.
lazy Delegate
Initialize a property only when first accessed.
Regex Find
Find a pattern in text using Regex.
Coroutine launch
Start a concurrent coroutine with launch.
async and await
Get a result from a concurrent coroutine.
Kotlin Flow
Emit and collect a stream of values.
Flow map Operator
Transform flow values with map.
Ranges and step
Iterate forward, backward, and with steps.
Sealed Class
Model limited states with sealed classes.
Enum Class
Define a fixed set of named constants.
suspend Function
Call a suspend function from runBlocking.
coroutineScope
Wait for child coroutines with coroutineScope.
withContext IO
Run blocking-style work on Dispatchers.IO.
Companion Factory
Create instances through a companion factory.
object Singleton
A singleton utility with object.
SharedFlow Event
Emit a one-time event with SharedFlow.