Hello everyone, If we have the following in Groov...
# announcements
g
Hello everyone, If we have the following in Groovy / Gradle:
Copy code
Closure a = { /*...*/ }
Closure b = { /*...*/ }
Closure c = a << b
How can we do that in Kotlin? Merging closures or high order functions? I’m trying something like:
Copy code
val a : KotlinSourceSet.() -> Unit = {
    dependencies {
        implementation(kotlin("stdlib-js"))
    }
}

val b: KotlinSourceSet.() -> Unit = {
    dependencies {
        implementation(project(":common", "jvmApiDefault"))
    }
}
where the result that I expect is something like:
Copy code
val c: KotlinSourceSet.() -> Unit = {
    dependencies {
        implementation(kotlin("stdlib-js"))

        implementation(project(":common", "jvmApiDefault"))
    }
}
But how can we properly create the variable
c
?
s
You mean composition of lambdas/closures?
If so, create a
andThen
or
compose
function, something like this:
infix fun <A, B, C> ((A) -> B).andThen(g: (B) -> C): (A) -> C = { a: A -> g(this(a)) }
Copy code
val c = a andThen b
g
My real case is the following:
Copy code
val a : KotlinSourceSet.() -> Unit = {
	dependencies {
		implementation(kotlin("stdlib-js"))
	}
}

val b: KotlinSourceSet.() -> Unit = {
	dependencies {
		implementation(project(":common", "jvmApiDefault"))
	}
}

val c: KotlinSourceSet.() -> Unit = {
	dependencies {
		implementation(kotlin("stdlib-js"))

		implementation(project(":common", "jvmApiDefault"))
	}
}
I’m needing this for a gradle script of mine. Where
c
is the result that I’m expecting.
Thanks @streetsofboston, this is an intersting code. But it is a bit complicated for my current knowledge of composing functions. Do you think we can achieve the expected result with something similar?
s
Just code it yourself for this particular use case:
val c : KotlinSourceSet.() -> Unit= { a(); b() }
Using
andThen
would be a generic solution for this
g
Hum, interesting. Thank you. I’ll try this solution and return 😃