Created
October 1, 2019 06:35
-
-
Save happy-bracket/a44d264a3f3562beaf4a40386afb4335 to your computer and use it in GitHub Desktop.
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
| fun main() { | |
| val res = caseOf("string", { | |
| case({ contains("s") }) { 1 } | |
| case({ contains("t") }) { 2 } | |
| }, orElse = { | |
| 3 | |
| }) | |
| } | |
| open class CaseOf<T, R>(private val receiver: T) { | |
| protected var result: R? = null | |
| fun case(condition: T.() -> Boolean, result: () -> R) { | |
| if (receiver.condition()) { | |
| this.result = result() | |
| } | |
| throw Interrupt | |
| } | |
| object Interrupt : Exception() | |
| } | |
| class ResultExtractor<T, R>(value: T) : CaseOf<T, R>(value) { | |
| fun extract() = result | |
| } | |
| fun <T, R> caseOf(value: T, body: CaseOf<T, R>.() -> Unit): R? { | |
| val context = ResultExtractor<T, R>(value) | |
| return try { | |
| context.body() | |
| context.extract() | |
| } catch (e: CaseOf.Interrupt) { | |
| null | |
| } | |
| } | |
| fun <T, R> caseOf(value: T, body: CaseOf<T, R>.() -> Unit, orElse: () -> R): R { | |
| return caseOf(value, body) ?: orElse() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment