Threading a parameter through multiple method calls


Given that Kotlin is a functional language, there are many instances where a single, immutable value is passed through a series of methods, each of which create a new, changed instance of that value and return it. This is especially true when using copy() on data objects.

For example: given Type A that is a data class, you might have methods:
fun mutateA1(a: A) = a.copy(field1 = field1+1)
fun mutateA2(a:A) = a.copy(field2 = field2*2)

A set of calls to these methods would look like:
(which gets messier with more methods and more parameters)

In Clojure, there is a keyword (technically a macro) called the “thread-first” macro ( that assists this scenario:
-> a

It would be nice if Kotlin adopted something similar, to encourage this sort of immutable design.


You can use extension methods

fun A.mutate1() = ...
fun A.mutate2() = ...