Fluent methods in Kotlin

suggest change

Fluent methods in Kotlin can be the same as Java:

class Worker {
    fun someOtherAction() { }

    fun doSomething(): Worker {
        someOtherAction()
        return this
    }
}

But you can also make them more functional by creating an extension function such as:

fun <T: Any> T.fluently(func: ()->Unit): T {
    func()
    return this
}

Which then allows more obviously fluent functions:

fun Worker.doSomethingFluently(): Worker {
    return fluently { someOtherAction() }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents