David Kubecka
01/24/2024, 11:29 AMopen class A
class B : A()
fun doWork(returnEarly: Boolean): A {
if (getValue().isError()) {
if (returnEarly) return A()
}
// do some expensive work
return B()
}
val b = doWork(false)
Is there any way to achieve that b
has type B
? The important thing here is the early return from the function, not the actual function signature. I.e. I can imagine that some lambda with clever types is passed instead of the boolean parameter.
For the actual use case see https://kotlinlang.slack.com/archives/C5UPMM0A0/p1706037300372059. I hope I have not overdistilled it here :-)Sam
01/24/2024, 11:44 AMMode
enum into a parameterised type.David Kubecka
01/24/2024, 3:33 PMdoWork
function can be much more complicated in reality and basically I would have to duplicate everything which has returnEarly
as a parameter and an early return anywhere in the body (possibly nested). I wonder whether a plain old exception (caught on the caller side with returnEarly=true
) wouldn't be simpler in this case 🙂Daniel Pitts
01/25/2024, 2:35 AMb is B
not work for you here?Daniel Pitts
01/25/2024, 2:38 AMgetOrThrow
when lenient.David Kubecka
01/25/2024, 10:28 AMI think the best approach is just to callYou probably to callwhen lenient.getOrThrow
getOrThrow
when strict 🙂 That's exactly what I was suggesting in my last sentence and I will probably go this way after all. It's still worth noting that this functional error handling method has its limitations (at least in Kotlin)Daniel Pitts
01/25/2024, 4:46 PMDavid Kubecka
01/25/2024, 5:39 PMcallService().getOrElse {
when (mode) {
LENIENT -> null
STRICT -> ... # throw or return Err
}
}