David Kubecka
01/23/2024, 7:15 PMResult
(from the kotlin-result library). If I get an error I would like to exit immediately (not processing the other elements), unless the outer function is called in a lenient mode, in which case I just ignore the particular result. The current implementation looks like this:
enum class Mode { STRICT, LENIENT }
object Error
object AnotherError
fun processList(intList: List<Int>, mode: Mode): Result<List<String>, AnotherError> {
val stringList = intList.mapNotNull {
processElement(it).getOrElse {
when (mode) {
Mode.STRICT -> return Err(AnotherError) // early return on first error
Mode.LENIENT -> null // ignore the error results
}
}
}
return Ok(stringList)
}
// some expensive computation
fun processElement(elem: Int): Result<String, Error> = Ok("$elem")
This works fine except there's a slight problem in the lenient mode where I need to handle the potential error result even though it can't happen:
fun processListLenient(intList: List<Int>): List<String> =
processList(intList, Mode.LENIENT).getOrElse { error("should not happen") }
This isn't very nice and I'm thinking whether there is a nicer way how to structure my code. Namely, I want processList
to return generic Result
in the strict mode, but specific Ok
in the lenient mode.raulraja
01/23/2024, 9:37 PMMode
types you can make them parametric so the result type depends on the mode you are using. For example:raulraja
01/23/2024, 9:42 PMraulraja
01/23/2024, 9:43 PMraulraja
01/23/2024, 9:45 PMraulraja
01/23/2024, 10:15 PMDavid Kubecka
01/24/2024, 6:25 AMDavid Kubecka
01/24/2024, 7:25 AM