This not strictly about Arrow but rather about fun...
# arrow
d
This not strictly about Arrow but rather about functional error handling so hope it's appropriate to ask here. I have a function which processes a list of elements by calling another function on each element. That inner function returns a
Result
(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:
Copy code
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:
Copy code
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.
r
Hi @David Kubecka, If you have control over your
Mode
types you can make them parametric so the result type depends on the mode you are using. For example:
Doesn't help much because you need two implementations
But I'm not sure it's possible to make the result type dependant on the Mode when just using a single function and an enumeration.
Parametric Mode.cpp
This is the same as having two different named functions without an enum at all. one for the strict and one for the lenient mode.
d
Yep, having to duplicate stuff indeed doesn't help much 😞
I think I actually need the ability to specify a lower bound in the typing. It seems that other people are asking about it as well: https://discuss.kotlinlang.org/t/generic-constraints-lower-bound/15074/10 and https://youtrack.jetbrains.com/issue/KT-18612/Provide-ability-to-specify-lower-bounds-for-generic-parameters