https://kotlinlang.org logo
Title
d

dio

07/20/2017, 4:35 PM
(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

hho

07/20/2017, 5:01 PM
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:
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

dio

07/20/2017, 5:02 PM
I like it
that allows me multiple functions
rather than the version I found from packt
thanks a ton