Created
May 21, 2022 14:11
-
-
Save gmk57/a407c9ce03833268ff91155004a1ed07 to your computer and use it in GitHub Desktop.
Implementation of Result.flatMap(), missing from Kotlin stdlib
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
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 } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 aroundResult
.Fortunately it can be trivially implemented on top of existing functions. See above for implementation & usage example.