Kotlin Examples

Every example includes runnable code and expected output. Filter by topic or difficulty.

46 examples

BeginnerBasics

Hello World

The simplest Kotlin program.

fun main() {
Output included
BeginnerBasics

Variables - val and var

Declare read-only and mutable variables.

fun main() {
Output included
BeginnerBasics

Data Types

Common Kotlin data types in one example.

fun main() {
Output included
BeginnerStrings

String Templates

Embed variables inside strings using $.

fun main() {
Output included
BeginnerOperators

Arithmetic Operators

Basic math operations in Kotlin.

fun main() {
Output included
BeginnerControl Flow

If / Else

Conditional logic with if and else.

fun main() {
Output included
BeginnerControl Flow

When Expression

Pattern matching with when.

fun main() {
Output included
BeginnerLoops

For Loop with Range

Iterate over a range of numbers.

fun main() {
Output included
BeginnerLoops

While Loop

Loop while a condition is true.

fun main() {
Output included
BeginnerFunctions

Basic Function

Define and call a simple function.

fun greet() {
Output included
BeginnerFunctions

Function with Return Value

Return a value from a function.

fun add(a: Int, b: Int): Int {
Output included
BeginnerFunctions

Default Arguments

Use default values for function parameters.

fun greetUser(name: String, role: String = "Student") {
Output included
BeginnerCollections

List Example

Create and access an immutable list.

fun main() {
Output included
BeginnerCollections

Mutable List

Add and remove items from a list.

fun main() {
Output included
BeginnerCollections

Map Example

Store key-value pairs in a map.

fun main() {
Output included
IntermediateCollections

filter and map

Filter and transform a list.

fun main() {
Output included
BeginnerOOP

Class Example

Define a class with properties.

class Car {
Output included
BeginnerOOP

Primary Constructor

Pass data into a class via its constructor.

class Student(val name: String, val age: Int)
Output included
IntermediateOOP

Inheritance

Extend a class and override a function.

open class Animal {
Output included
BeginnerOOP

Data Class

Automatic toString, equals, and copy.

data class User(val name: String, val age: Int)
Output included
BeginnerNull Safety

Nullable Variable

Declare variables that can hold null.

fun main() {
Output included
BeginnerNull Safety

Safe Call Operator

Access properties of nullable values safely.

fun main() {
Output included
BeginnerNull Safety

Elvis Operator

Provide a fallback when a value is null.

fun main() {
Output included
BeginnerNull Safety

Smart Cast

Automatically cast after a type check.

fun printLength(value: Any) {
Output included
BeginnerLambdas

Lambda Expression

Use a lambda to transform a list.

fun main() {
Output included
IntermediateLambdas

Higher-Order Function

Pass a function as a parameter.

fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
Output included
IntermediateLambdas

Extension Function

Add functions to existing types.

fun String.greet(): String {
Output included
IntermediateLambdas

apply Scope Function

Configure an object using apply.

data class Person(var name: String, var age: Int)
Output included
BeginnerExceptions

try catch finally

Handle runtime errors gracefully.

fun main() {
Output included
IntermediateGenerics

Generic Class

Create a class that works with any type.

class Box<T>(val value: T)
Output included
IntermediateAdvanced

Destructuring Declarations

Unpack data class properties into variables.

data class User(val name: String, val age: Int)
Output included
IntermediateAdvanced

lazy Delegate

Initialize a property only when first accessed.

fun main() {
Output included
IntermediateStandard Library

Regex Find

Find a pattern in text using Regex.

fun main() {
Output included
IntermediateCoroutines

Coroutine launch

Start a concurrent coroutine with launch.

import kotlinx.coroutines.*
Output included
IntermediateCoroutines

async and await

Get a result from a concurrent coroutine.

import kotlinx.coroutines.*
Output included
IntermediateFlow

Kotlin Flow

Emit and collect a stream of values.

import kotlinx.coroutines.*
Output included
IntermediateFlow

Flow map Operator

Transform flow values with map.

import kotlinx.coroutines.*
Output included
BeginnerControl Flow

Ranges and step

Iterate forward, backward, and with steps.

fun main() {
Output included
IntermediateOOP

Sealed Class

Model limited states with sealed classes.

sealed class Result
Output included
BeginnerOOP

Enum Class

Define a fixed set of named constants.

enum class Direction { NORTH, SOUTH, EAST, WEST }
Output included
IntermediateCoroutines

suspend Function

Call a suspend function from runBlocking.

import kotlinx.coroutines.*
Output included
IntermediateCoroutines

coroutineScope

Wait for child coroutines with coroutineScope.

import kotlinx.coroutines.*
Output included
IntermediateCoroutines

withContext IO

Run blocking-style work on Dispatchers.IO.

import kotlinx.coroutines.*
Output included
BeginnerOOP

Companion Factory

Create instances through a companion factory.

class Token private constructor(val value: String) {
Output included
BeginnerOOP

object Singleton

A singleton utility with object.

object AppConfig {
Output included
IntermediateFlow

SharedFlow Event

Emit a one-time event with SharedFlow.

import kotlinx.coroutines.*
Output included