Skip to content

Instantly share code, notes, and snippets.

@sorokod
Last active January 8, 2022 17:13
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 sorokod/99d83e5ff5db9faf55c5a9bf5a81cb1e to your computer and use it in GitHub Desktop.
Save sorokod/99d83e5ff5db9faf55c5a9bf5a81cb1e to your computer and use it in GitHub Desktop.
Abusing Result.mapCatching() to implement a chain of transformations validations
/**
* Abusing Result.mapCatching() to implement a chain
* of transformations / validations
*/
/** A convenience thing **/
inline fun <reified T> fail(msg: String): T = throw IllegalArgumentException(msg)
/** **/
fun validSize(requiredSize: Int, list: List<String>): List<String> =
when (list.size <= requiredSize) {
true -> list
else -> fail("Invalid size ${list.size}")
}
/** All elements can be converted to Ints **/
fun validData(list: List<String>): List<Int> =
if (list.map { it.toIntOrNull() }.all { it != null }) {
list.map { it.toInt() }
} else {
fail("Not all Ints $list")
}
/** **/
fun validSum(requiredSum: Int, list: List<Int>): Int =
when (list.sum() <= requiredSum) {
true -> list.sum()
else -> fail("Invalid list sum: ${list.sum()}")
}
fun tryOut(data: List<String>) {
Result.success(data)
.mapCatching { validSize(3, it) }
.mapCatching { validData(it) }
.mapCatching { validSum(10, it) }
.fold(
onSuccess = { println("OK> $it") },
onFailure = { println("FAILED> ${it.message}") }
)
}
fun main() {
tryOut(listOf("a", "b", "c", "d")) // FAILED> Invalid size 4
tryOut(listOf("a", "b", "c")) // FAILED> Not all Ints [a, b, c]
tryOut(listOf("100")) // FAILED> Invalid list sum: 100
tryOut(listOf("101", "-1")) // // FAILED> Invalid list sum: 100
tryOut(listOf("-1", "11", "-2")) // OK> 8
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment