Skip to content

Instantly share code, notes, and snippets.

@barthap
Last active August 10, 2020 18:10
Show Gist options
  • Save barthap/b779ed0467482b522ba3d38c1aa905e3 to your computer and use it in GitHub Desktop.
Save barthap/b779ed0467482b522ba3d38c1aa905e3 to your computer and use it in GitHub Desktop.
Kotlin and its cool functions

Kotlin and its cool functions

Ketchup Kotlin

Table of contents

Official page is here

apply

inline fun <T> T.apply(block: T.() -> Unit): T

The context object is available as a receiver (this). The return value is the object itself.

Example:

class User(var name: String, var age: Int)
val user = User("John", 25) //John, 25

val anotherUser = user.apply {
    age = 32
} //John, 32

also

inline fun <T> T.also(block: (T) -> Unit): T

The context object is available as an argument (it). The return value is the object itself.

Example:

data class User(val name: String, val age: Int)
val user = User("John", 25)

user.also {
    println("I'm ${it.name} and I'm ${it.age} years old")
}

let

inline fun <T, R> T.let(block: (T) -> R): R

The context object is available as an argument (it). The return value is lambda result

Example:

data class User(val name: String, val age: Int)
val user = User("John", 25)

val ageAfter5Years = user.let { it.age + 5 }    // 30

run

The context object is available as a receiver (this). The return value is lambda result.

Example:

data class User(val name: String, val age: Int)
val user = User("John", 25)

val nameUppercase = user.run { name.toUpperCase() } //JOHN

It can also run without context object

val area = run {
    val r = 20.0
    const val PI = 3.1415
    PI*r*r
}

with

Example:

class User(val name: String, val age: Int) {
    fun indroduce() {
        println("I'm ${it.name} and I'm ${it.age} years old")
    }
}
val user = User("John", 25)

with(user) {
    println("Introducing ${name}")
    this.introduce()
}

use

Used with Closeables. Calls close() at the end of the block

Example:

Files.newOutputStream(path).use {
    it.write("Hello")
} //close() is called here

Custom one

To define as this:

class Dog(var name: String) {
    fun bark() { println("Woof woof") }
}

fun Dog.doStuff(block: Dog.() -> Unit) {
    println("Doing dog stuff...")
    block(this)
}

val dog = Dog("Bob")

dog.doStuff {
    println("I'm $name")
    bark()
}

To define as it:

class Cat(var name: String) {
    fun meaw() { println("Meaow!") }
}

fun Cat.doStuff(block: (Cat) -> Unit) {
    println("Doing cat stuff...")
    block(this)
}

val cat = Dog("Kitty")

cat.doStuff {
    println("I'm ${it.name}")
    it.meaow()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment