Kotlin is all about simplifying the development. Kotlin’s standard library is full of useful classes and functions which aim to fulfill this promise even where the built-in language features don’t exist. One of such groups of functions in standard library are Kotlin’s higher order functions apply, let, run, with and also.

These functions allow you to write more concise, simpler code by removing code duplication. Warning! Once you start using them, you won’t be able to imagine coding without them!

This post contains all the code that’s been written in this YouTube video.

fun main(args: Array<String>){
    val firstPerson = Person("John", 20, "Programmer")
    val secondPerson = Person("Dave", 30, "Bus Driver")

    val olderPerson = if (firstPerson.age >= secondPerson.age) firstPerson else secondPerson
    olderPerson.printPerson()

    run {
        if (firstPerson.age >= secondPerson.age) firstPerson else secondPerson
    }.printPerson()

    with(firstPerson) {
        age += 1
        "Age is now $age"
    }.println()

    firstPerson.run {
        age += 1
        "Age is now $age"
    }.println()

    firstPerson.let { modifiedPerson ->
        modifiedPerson.age += 1
        "Age is now ${modifiedPerson.age}"
    }.println()

    secondPerson.apply {
        age += 1
        job = "Hot-dog seller"
    }.printPerson()

    secondPerson.also {
        it.age += 1
        it.job = "YouTuber"
    }.printPerson()
}

data class Person(var name: String,
                  var age: Int,
                  var job: String) {
    fun printPerson() = println(this.toString())
}

fun String.println() = println(this)

About the author 

Matt Rešetár

Matt is an app developer with a knack for teaching others. Working as a Flutter freelancer and most importantly developer educator, he doesn't have a lot of free time 😅 Yet he still manages to squeeze in tough workouts 💪

You may also like

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
>