Skip to content

Instantly share code, notes, and snippets.

@fbiville
Last active March 1, 2019 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fbiville/d489cd33b79314d5eca3fb17b22297ff to your computer and use it in GitHub Desktop.
Save fbiville/d489cd33b79314d5eca3fb17b22297ff to your computer and use it in GitHub Desktop.
kotlin.Result - flatMap extension
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