Early return of a fold

Asked

Viewed 75 times

6

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

Example of documentation:

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

In that spirit, I would like to make a lambda expression return in advance a fold. That is to say:

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 that case I’d like to get 6 (early return of function fold in 3 + 2 + 1). However, it seems that the return@fold is simply returning from the lambda expression and continuing with the fold normally (result 10 = 3 + 2 + 1 + 4).

Is there any way to make that early return?

  • This language feature looks pretty cool, I don’t know almost anything yet but I like Kotlin. This would be something like yield? Expression lambida :D

  • I’m also trying to explore. I liked it a lot (a good middle ground between Scala and Java). It seems they have plans to support yield officially in the future. This is more to Labels on Steroids :).

  • @mustache, I only saw the expression "lick" now hehehe. Thanks.

1 answer

2


The best workaround that I found was to wrap the fold with a IIFE (javascript style). This way I can use return sum with no one 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 from the anonymous function that wraps the fold. There must be a less ugly way to do this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.