Last active
January 8, 2022 17:13
-
-
Save sorokod/99d83e5ff5db9faf55c5a9bf5a81cb1e to your computer and use it in GitHub Desktop.
Abusing Result.mapCatching() to implement a chain of transformations validations
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
/** | |
* 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