Last active
March 1, 2019 16:40
-
-
Save fbiville/d489cd33b79314d5eca3fb17b22297ff to your computer and use it in GitHub Desktop.
kotlin.Result - flatMap extension
This file contains 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
import net.jqwik.api.ForAll | |
import net.jqwik.api.Property | |
// requires compiler option '-Xallow-result-return-type' | |
fun <T, U> Result<T>.flatMap(function: (T) -> Result<U>): Result<U> { | |
return if (isSuccess) { | |
function(getOrNull()!!) | |
} else { | |
Result.failure(this.exceptionOrNull()!!) | |
} | |
} | |
class ResultExtensionsTest { | |
@Property | |
fun `flatmap check -- monad left identity`(@ForAll value: String): Boolean { | |
val initial = point(value) | |
return initial.flatMap(::f) == f(value) | |
} | |
@Property | |
fun `flatmap check -- monad right identity`(@ForAll value: String): Boolean { | |
val initial = f(value) | |
return initial.flatMap { point(it) } == initial | |
} | |
@Property | |
fun `flatmap check -- monad associativity`(@ForAll value: String): Boolean { | |
val initial = point(value) | |
return initial.flatMap(::f).flatMap(::g) == initial.flatMap { f(it).flatMap(::g) } | |
} | |
companion object { | |
fun f(s: String) = Result.success("$s something") | |
fun g(s: String) = Result.success("$s nonething") | |
fun <T> point(x: T): Result<T> = Result.success(x) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment