Top 30 Trending Kotlin Coding Examples

1. Write a Kotlin function to reverse a string in place or using built-in methods

Code:

fun reverseString(str: String): String {
    return str.reversed()
}

fun main() {
    println(reverseString("Kotlin"))
}

Output:

niltoK

Explanation: Kotlin’s extension function reversed() returns a new string with characters in reverse order.

2. Check if a string is a palindrome in Kotlin

Code:

fun isPalindrome(str: String): Boolean {
    const cleanStr = str.lowercase().replace(Regex("[^a-z0-9]"), "")
    return cleanStr == cleanStr.reversed()
}

fun main() {
    println(isPalindrome("RaceCar"))
}

Output:

true

Explanation: Converts the string to lowercase, strips non-alphanumeric characters using regex, and compares it with its reversed counterpart.

3. Demonstrate Kotlin’s Null Safety with the safe call operator and Elvis operator

Code:

fun main() {
    val name: String? = null
    val length = name?.length ?: 0
    println("Name length: $length")
}

Output:

Name length: 0

Explanation: The safe call operator ?. evaluates to null if the variable is null, and the Elvis operator ?: provides a default value when the left-hand side is null.

4. Create a concise Data Class with default values and destructuring support

Code:

data class User(val name: String, val age: Int = 18)

fun main() {
    val user = User("Alice", 25)
    val (name, age) = user
    println("$name is $age years old.")
}

Output:

Alice is 25 years old.

Explanation: Kotlin Data Classes automatically generate equals(), hashCode(), toString(), copy(), and componentN() functions for destructuring declarations.

5. Filter and map collections using Kotlin High-Order Functions.

Code:

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5, 6)
    val result = numbers.filter { it % 2 == 0 }.map { it * it }
    println(result)
}

Output:

[4, 16, 36]

Explanation: filter keeps only even numbers, and map transforms each remaining element by squaring it.

6. Solve the Two Sum problem in Kotlin using a HashMap

Code:

fun twoSum(nums: IntArray, target: Int): IntArray {
    val map = hashMapOf<Int, Int>()
    for ((index, num) in nums.withIndex()) {
        val diff = target - num
        if (map.containsKey(diff)) {
            return intArrayOf(map!!, index)
        }
        map[num] = index
    }
    return intArrayOf()
}

fun main() {
    val result = twoSum(intArrayOf(2, 7, 11, 15), 9)
    println(result.joinToString())
}

Output:

0, 1

Explanation: Uses a HashMap to look up target complements in O(1) time complexity while iterating through the array once.

7. Create an Extension Function for the String class in Kotlin

Code:

fun String.removeSpaces(): String {
    return this.replace("\\s+".toRegex(), "")
}

fun main() {
    val text = "Kotlin Extension Functions"
    println(text.removeSpaces())
}

Output:

KotlinExtensionFunctions

Explanation: Extension functions allow adding new member methods to existing classes without modifying their original source code.

8. Use Smart Casts and ‘when’ expression as a pattern-matching mechanism with Kotlin

Code:

fun process(obj: Any): String = when (obj) {
    is String -> "String length: ${obj.length}"
    is Int -> "Integer squared: ${obj * obj}"
    else -> "Unknown type"
}

fun main() {
    println(process("Kotlin"))
    println(process(5))
}

Output:

String length: 6
Integer squared: 25

Explanation: The ‘when’ expression performs type checks with ‘is’, and Kotlin automatically smart-casts the variable to the target type within that branch.

9. Execute asynchronous concurrent tasks using Kotlin Coroutines (async/await) with Kotlin

Code:

import kotlinx.coroutines.*

fun main() = runBlocking {
    val deferred1 = async { fetchData(100) }
    val deferred2 = async { fetchData(200) }
    val sum = deferred1.await() + deferred2.await()
    println("Total: $sum")
}

suspend fun fetchData(value: Int): Int {
    delay(100)
    return value
}

Output:

Total: 300

Explanation: async launches lightweight coroutines concurrently, and await() suspends execution non-blockingly until the deferred value is computed.

10. Create Restricted Class Hierarchies using Sealed Classes in Kotlin

Code:

sealed class Result
data class Success(val data: String) : Result()
data class Error(val exception: String) : Result()

fun handleResult(result: Result) = when (result) {
    is Success -> "Data: ${result.data}"
    is Error -> "Error: ${result.exception}"
}

fun main() {
    println(handleResult(Success("OK")))
}

Output:

Data: OK

Explanation: Sealed classes represent restricted class hierarchies, enabling exhaustive type handling in ‘when’ expressions without an ‘else’ block.

11. Perform Scope Functions using let, run, with, apply, and also in Kotlin

Code:

fun main() {
    val name = "Kotlin"
    name.let {
        println("The length of $it is ${it.length}")
    }

    val list = mutableListOf(1, 2).apply {
        add(3)
        add(4)
    }
    println(list)
}

Output:

The length of Kotlin is 6
[1, 2, 3, 4]

Explanation: Scope functions execute code blocks within the context of an object, providing object references via ‘it’ or ‘this’.

12. Lazy Initialization in Kotlin using ‘by lazy’.

Code:

val heavyResource: String by lazy {
    println("Computed once!")
    "Resource Loaded"
}

fun main() {
    println("Before access")
    println(heavyResource)
    println(heavyResource)
}

Output:

Before access
Computed once!
Resource Loaded
Resource Loaded

Explanation: The ‘by lazy’ delegate delays property initialization until its first access and caches the computed result for subsequent calls.

13. Group collection elements by key using groupBy in Kotlin

Code:

fun main() {
    val words = listOf("apple", "apricot", "banana", "berry")
    val grouped = words.groupBy { it.first() }
    println(grouped)
}

Output:

{a=[apple, apricot], b=[banana, berry]}

Explanation: groupBy partitions items into a Map where keys are calculated by the provided lambda selector.

14. Flatten nested collections using flatMap in Kotlin

Code:

fun main() {
    val nestedList = listOf(listOf("A", "B"), listOf("C", "D"))
    val flat = nestedList.flatMap { it }
    println(flat)
}

Output:

[A, B, C, D]

Explanation: flatMap transforms each element into an iterable and flattens the resulting collections into a single list.

15. Create custom Singleton objects using object declarations in Kotlin

Code:

object DatabaseConfig {
    val url: String = "jdbc:mysql://localhost:3306/db"
    fun connect() = "Connected to $url"
}

fun main() {
    println(DatabaseConfig.connect())
}

Output:

Connected to jdbc:mysql://localhost:3306/db

Explanation: The ‘object’ keyword in Kotlin declares a thread-safe Singleton instance lazily initialized upon first usage.

16. Use Companion Objects as class static factories or properties in Kotlin

Code:

class Car(val model: String) {
    companion object {
        fun createTesla(): Car = Car("Tesla Model S")
    }
}

fun main() {
    val car = Car.createTesla()
    println(car.model)
}

Output:

Tesla Model S

Explanation: Companion objects provide static-like factory methods and properties tied to class definitions rather than class instances.

17. Generate asynchronous data streams using Kotlin Flow

Code:

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun numberFlow(): Flow<Int> = flow {
    for (i in 1..3) {
        emit(i)
    }
}

fun main() = runBlocking {
    numberFlow().collect { value -> println(value) }
}

Output:

1
2
3

Explanation: Kotlin Flow is a cold asynchronous stream that emits values sequentially when collected inside coroutine scopes.

18. Define Custom Infix Functions in Kotlin

Code:

infix fun Int.times(str: String): String {
    return str.repeat(this)
}

fun main() {
    val result = 3 times "Hi "
    println(result)
}

Output:

Hi Hi Hi

Explanation: Member or extension functions marked with ‘infix’ can be called omitting dots and parentheses for domain-specific syntax.

19. Process large data collections lazily using Sequences in Kotlin

Code:

fun main() {
    val numbers = (1..1000).asSequence()
    val result = numbers.filter { it % 2 == 0 }
                        .map { it * 2 }
                        .take(3)
                        .toList()
    println(result)
}

Output:

[4, 8, 12]

Explanation: Sequences perform transformations lazily element by element, avoiding intermediate list allocations during chaining.

20. Use Inline Classes / Value Classes to avoid memory allocation overhead in Kotlin

Code:

@JvmInline
value class UserId(val id: Long)

fun main() {
    val user = UserId(1001L)
    println("User ID: ${user.id}")
}

Output:

User ID: 1001

Explanation: Value classes wrap primitive or object types without runtime allocation overhead by inlining values into underlying types.

21. Destructure pair and triple objects in Kotlin

Code:

fun getCoordinates(): Triple<Int, Int, Int> {
    return Triple(10, 20, 30)
}

fun main() {
    val (x, y, z) = getCoordinates()
    println("X: $x, Y: $y, Z: $z")
}

Output:

X: 10, Y: 20, Z: 30

Explanation: Kotlin built-in types Pair and Triple support component destructuring out of the box.

22. Handle Exceptions using ‘try’ as an Expression in Kotlin

Code:

fun main() {
    val input = "abc"
    val number: Int? = try {
        input.toInt()
    } catch (e: NumberFormatException) {
        null
    }
    println("Parsed number: $number")
}

Output:

Parsed number: null

Explanation: In Kotlin, ‘try’ is an expression whose returned value is the last expression in the try or catch block.

23. Sort a custom object list using compareBy selector in Kotlin

Code:

data class Product(val name: String, val price: Double)

fun main() {
    val products = listOf(
        Product("Laptop", 1200.0),
        Product("Phone", 800.0),
        Product("Tablet", 500.0)
    )
    val sorted = products.sortedWith(compareBy { it.price })
    println(sorted.map { it.name })
}

Output:

[Tablet, Phone, Laptop]

Explanation: sortedWith combined with compareBy orders collection elements based on target member attributes.

24. Implement Delegation using the ‘by’ keyword in Kotlin

Code:

interface Printer {
    fun printMessage()
}

class ConsolePrinter : Printer {
    override fun printMessage() = println("Delegated Printing")
}

class DelegationLogger(printer: Printer) : Printer by printer

fun main() {
    val logger = DelegationLogger(ConsolePrinter())
    logger.printMessage()
}

Output:

Delegated Printing

Explanation: Class delegation using ‘by’ forwards public interface member invocations to enclosed implementation instances natively.

25. Remove duplicate elements from a list preserving insertion order in Kotlin

Code:

fun main() {
    val items = listOf("A", "B", "A", "C", "B")
    val uniqueItems = items.distinct()
    println(uniqueItems)
}

Output:

[A, B, C]

Explanation: The distinct() extension function strips duplicates while maintaining original element ordering.

26. Measure code block execution time in Kotlin using measureTimeMillis

Code:

import kotlin.system.measureTimeMillis

fun main() {
    val time = measureTimeMillis {
        var sum = 0L
        for (i in 1..1_000_000) {
            sum += i
        }
    }
    println("Executed in $time ms")
}

Output:

Executed in 12 ms

Explanation: measureTimeMillis executes the passed block lambda and measures overall elapsed wall-clock time in milliseconds.

27. Partition a collection into two lists using a predicate condition.

Code:

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5, 6)
    val (evens, odds) = numbers.partition { it % 2 == 0 }
    println("Evens: $evens")
    println("Odds: $odds")
}

Output:

Evens: [2, 4, 6]
Odds: [1, 3, 5]

Explanation: partition splits a collection into a Pair of lists where the first contains items matching the predicate and the second contains the rest.

28. Use ‘reified’ type parameters with inline functions to access generics at runtime in Kotlin

Code:

inline fun <reified T> printTypeInfo(value: Any) {
    if (value is T) {
        println("Value matches type ${T::class.simpleName}")
    }
}

fun main() {
    printTypeInfo<String>("Hello")
}

Output:

Value matches type String

Explanation: Reified parameters coupled with inline functions prevent generic type erasure, granting access to type metadata at runtime.

29. Compute element accumulation using reduce and fold functions in Kotlin

Code:

fun main() {
    val numbers = listOf(1, 2, 3, 4)
    val sum = numbers.fold(10) { acc, num -> acc + num }
    println("Sum with initial value 10: $sum")
}

Output:

Sum with initial value 10: 20

Explanation: fold accumulates values starting from an initial value and applies the operation lambda left to right.

30. Create Range and Progression iterations using step and downTo in Kotlin

Code:

fun main() {
    for (i in 10 downTo 2 step 2) {
        print("$i ")
    }
}

Output:

10 8 6 4 2

Explanation: downTo creates reverse progressions, and step sets the decrement step interval per iteration.


If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.


For Videos, Join Our YouTube Channel: Join Now


Recommended Posts

Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment