Examples

Kotlin examples

Write concise, typed code for JVM applications.

15 examples

Kotlin Basics

Use values and string templates.

Kotlin

Kotlin Lists

Process an ordered collection.

Kotlin

Kotlin Functions

Declare typed parameters and a return type.

Kotlin

Kotlin when Expressions

Choose a result from several conditions with when.

Kotlin

Kotlin null safety

Distinguish nullable from non-null types, and use ?., ?:, let, and !! deliberately.

Kotlin

Kotlin collections and higher-order functions

Filter, map, group, sort, and fold lists with lambdas instead of loops.

Kotlin

Kotlin Classes

Declare a class with a primary constructor and private state.

Kotlin

Kotlin data classes and sealed interfaces

Model alternatives with a sealed hierarchy and let the compiler check that every case is handled.

Kotlin

Kotlin object, companion object, and delegation

Create singletons, class-level factories with private constructors, and reuse behaviour by delegating to an interface.

Kotlin

Kotlin sorting and binary search

Sort lists with sorted and sortedBy, and find a value or its insertion point with binarySearch.

Kotlin

Kotlin ArrayDeque as a stack and a queue

Check balanced brackets with a stack and serve items in arrival order with a queue.

Kotlin

Kotlin maps: counting and indexing

Count words with groupingBy and build a lookup map with getOrPut.

Kotlin

Kotlin unit tests with lambdas and runCatching

Write a minimal test function that reports passes and failures, including expected exceptions.

Kotlin

Kotlin SHA-256 and PBKDF2 on the JVM

Hash text with MessageDigest and derive a salted password hash with PBKDF2.

Kotlin

Kotlin threads, AtomicInteger, and an executor

Start threads that update a shared counter safely and split a sum across a thread pool.

Kotlin