Skip to content

Instantly share code, notes, and snippets.

@gmk57
Created May 21, 2022 14:11
Show Gist options
  • Save gmk57/a407c9ce03833268ff91155004a1ed07 to your computer and use it in GitHub Desktop.
Save gmk57/a407c9ce03833268ff91155004a1ed07 to your computer and use it in GitHub Desktop.
Implementation of Result.flatMap(), missing from Kotlin stdlib
inline fun <R, T> Result<T>.flatMap(transform: (T) -> Result<R>): Result<R> =
fold({ transform(it) }, { Result.failure(it) })
fun main() {
getUserInput()
.flatMap { input -> parseInput(input) }
.flatMap { numbers -> calculateMax(numbers) }
.onSuccess { maxNumber -> println("max: $maxNumber") }
.onFailure { throwable -> throwable.printStackTrace() }
}
// fails on empty input
fun getUserInput(): Result<String> = runCatching { readln().ifEmpty { error("empty") } }
// fails on non-numbers
fun parseInput(input: String): Result<List<Int>> =
runCatching { input.split(" ").mapNotNull { if (it.isBlank()) null else it.toInt() } }
// fails on " " input
fun calculateMax(numbers: List<Int>) = runCatching { numbers.maxOf { it } }
@gmk57
Copy link
Author

gmk57 commented May 21, 2022

I find Kotlin Result type very convenient for functional-style error handling and other uses cases described in the corresponding KEEP.

One thing that is missing from the Kotlin standard library is Result.flatMap(). There are specific reasons behind this decision, but nevertheless sometimes it would be useful for combining APIs designed around Result.

Fortunately it can be trivially implemented on top of existing functions. See above for implementation & usage example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment