Created
June 5, 2019 21:58
-
-
Save elizarov/ad1061603f75abde5867aa8f34d32361 to your computer and use it in GitHub Desktop.
Simple wrapper function combinator engine for Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ============ 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