Skip to content

Instantly share code, notes, and snippets.

@Kalimaha
Last active June 11, 2019 06:47
Show Gist options
  • Select an option

  • Save Kalimaha/e2e8d3a976539f7805617807e784b7d1 to your computer and use it in GitHub Desktop.

Select an option

Save Kalimaha/e2e8d3a976539f7805617807e784b7d1 to your computer and use it in GitHub Desktop.
Attempt to chain Kotlin's Result
private fun first(a: Int): Result<Int?> =
when(a % 2 == 0) {
true -> Result.success(value = a)
false -> Result.failure(Exception("$a is odd"))
}
private fun second(a: Int?): Result<Int?> = Result.failure(Exception("Because!"))
private fun third(a: Int?): Result<Int?> =
when(a?.compareTo(10)) {
0 -> Result.success(value = a)
else -> Result.failure(Exception("$a is too big"))
}
@Test
fun `It chains monads`() {
var out = first(a = 2).map { firstOutput -> second(a = firstOutput) }.map { secondOutput -> third(a = secondOutput.getOrNull()) }.map { firstOutput -> second(a = firstOutput.getOrNull()) }
if (out.isSuccess) {
println("YO!")
println(out.getOrNull())
} else {
println(out)
println("Nah...")
println(out.getOrNull())
}
}
# with https://github.com/michaelbull/kotlin-result#chaining
private fun uno(a: Int): com.github.michaelbull.result.Result<Int, String> =
when(a % 2 == 0) {
true -> Ok(value = a)
false -> Err("$a is odd")
}
private fun due(a: Int): com.github.michaelbull.result.Result<Int, String> =
when(a < 10) {
true -> Ok(value = a)
false -> Err("$a is too big")
}
@Test
fun `Chain Eithers`() {
var out_1 = uno(a = 40).andThen(::due)
when(out_1) {
is Ok -> println(out_1.get())
is Err -> println(out_1.getError())
}
var out_2 = uno(a = 4).andThen(::due)
when(out_2) {
is Ok -> println(out_2.get())
is Err -> println(out_2.getError())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment