(I'm coming from clojure) is there a way to thread...
# getting-started
d
(I'm coming from clojure) is there a way to thread results in kotlin? Imagine I have
fun foo(x: Int): Int
fun bar(x: Int): Int
fun baz(x: Int): Int
I could
baz(bar(foo(5)))
but that starts to feel nested and gross, in clojure I can say
(-> 5 foo bar baz)
to feed the results of one function call into the next and un-nest my calls, I'm wondering if there's some equivalent ?
h
I don't think, there's a 100% equivalent, because of static typing. However, your example has all functions having the same input & output types. That can be done:
Copy code
fun foo(input: Int) = 2 * input
fun bar(input: Int) = input + 2
fun baz(input: Int) = input / 2

fun <T> applyComposite(start: T, vararg functions: (T) -> T) : T {
	var result = start
	functions.forEach { result = it.invoke(result) }
	return result
}

fun main(args: Array<String>) {
	applyComposite(5, ::foo, ::bar, ::baz)
}
d
I like it
that allows me multiple functions
rather than the version I found from packt
thanks a ton