Preceded fold return

6

Kotlin allows returns for previously declared tags , including implicit tags.

Documentation example:

fun foo() {
  ints.forEach {
    if (it == 0) return@forEach
    print(it)
  }
}

In this spirit, I would like to make a lambda expression return in advance a fold . This is:

val array = intArrayOf(3, 2, 1, 4)
val firstEvenSum = array.fold(0, {acc, n -> 
    val sum = acc + n
    if (sum % 2 == 0)
      return@fold sum
    sum                              
})
println("First even sum is: $firstEvenSum")

In this case I would like to get 6 (early return of the fold function in 3 + 2 + 1 ). However, it seems that return@fold is simply returning the lambda expression and continuing with fold normally (result 10 = 3 + 2 + 1 + 4 ).

Is there any way to make this early return?

    
asked by anonymous 01.01.2016 / 15:58

1 answer

2

The best workaround I found was wrapping fold with a IIFE (JavaScript style). That way I can use return sum without any label .

val firstEvenSum = fun(): Int {
    array.fold(0, {acc, n -> 
        val sum = acc + n
        if (sum % 2 == 0)
            // retorna da funcao anonima, nao da expressao lambda
            return sum
        sum  
    })
    throw NoSuchElementException("No partial even sums") 
}();

On the other hand theoretically I'm not returning from the fold but rather from the anonymous function that wraps the fold. There must be a less ugly way to do it.

    
01.01.2016 / 17:27