Skip to content

Instantly share code, notes, and snippets.

@happy-bracket
Created October 1, 2019 06:35
Show Gist options
  • Save happy-bracket/a44d264a3f3562beaf4a40386afb4335 to your computer and use it in GitHub Desktop.
Save happy-bracket/a44d264a3f3562beaf4a40386afb4335 to your computer and use it in GitHub Desktop.
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