Skip to content

Instantly share code, notes, and snippets.

@mzaimilzam
Forked from gmk57/ResultFlatMap.kt
Created January 16, 2024 08:27
Show Gist options
  • Save mzaimilzam/fa2dc987b202e8f93a3f17b8ac84547f to your computer and use it in GitHub Desktop.
Save mzaimilzam/fa2dc987b202e8f93a3f17b8ac84547f 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 } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment