Skip to content

Instantly share code, notes, and snippets.

@elizarov
Created June 5, 2019 21:58
Show Gist options
  • Save elizarov/ad1061603f75abde5867aa8f34d32361 to your computer and use it in GitHub Desktop.
Save elizarov/ad1061603f75abde5867aa8f34d32361 to your computer and use it in GitHub Desktop.
Simple wrapper function combinator engine for Kotlin
// ============ test functions ============
fun withTransactional() = transactional {
println("withTransactional body")
}
fun withLogged() = logged {
println("withLogged body")
}
fun foo() = (logged + transactional) {
println("foo body")
}
fun main() {
withTransactional()
withLogged()
foo()
}
// ============ wrappers ============
val transactional = wrapper {
println("before transational")
try { it() } finally {
println("after transactional")
}
}
val logged = wrapper {
println("before logged")
try { it() } finally {
println("after logged")
}
}
// ============ engine impl ============
fun wrapper(impl: (() -> Unit) -> Unit): Wrapper = object : Wrapper() {
override fun impl(it: () -> Unit) = impl(it)
}
abstract class Wrapper {
abstract fun impl(it: () -> Unit)
operator fun <R> invoke(body: () -> R): R {
var result: R? = null
impl { result = body() }
@Suppress("UNCHECKED_CAST")
return result as R
}
operator fun plus(other: Wrapper) = wrapper {
impl {
other.impl { it() }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment