-
-
Save mzaimilzam/fa2dc987b202e8f93a3f17b8ac84547f 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