I wonder if there is a more idiomatic/concise way to return to the first success result or the last failure.
I have forEach
loop with an auxiliary variable and let
:
@Test
fun `find first success`() {
val keysToTry = listOf("foo", "bar", "baz")
val result = returnFirstSuccess(keysToTry)
}
fun returnFirstSuccess(keys: List<String>): Result {
var lastTry : Result? = null
keys.forEach { key ->
tryKey(key).let { result ->
if (result is Result.Success) {
return result
}else{
lastTry = result
}
}
}
return lastTry!!
}
fun tryKey(key: String): Result {
// if key passes return Sucess, otherwise Failure
}
sealed class Result {
object Success : Result()
data class Failure(val message: String) : Result()
}