Threading a parameter through multiple method calls


#1

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:
mutateA2(mutateA1(a))
(which gets messier with more methods and more parameters)

In Clojure, there is a keyword (technically a macro) called the “thread-first” macro (https://clojure.org/guides/threading_macros) that assists this scenario:
-> a
mutateA1()
mutateA2()

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


#2

You can use extension methods

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

a.mutate1()
 .mutate2()