How can I express else branches of for loops in ko...
# announcements
h
How can I express else branches of for loops in kotlin? Python supports this (imho obscure feature) (see https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops), but I want/need to port some python code to kotlin. In python the
else
after a for loop it is executed when the loop terminates through exhaustion of the iterable but not when the loop is terminated by a 
break
 statement.
Here is the yet non-functional example from the python docs ported to kotlin
Copy code
for(n in (2..10)){
    for(x in (2.. n)){
        if(n.rem(x)==0){
            println("$n equals $x * ${n/x} ")
            break
        }
    }
    //todo else{ ???
    // loop fell through without finding a factor
    println("$ is a prime number")
}
d
You can use an explicit iterator: https://pl.kotl.in/B6NAiEUez
1
h
Great solution. Vielen Dank!
a
wow, TIL 😱
n
An alternative solution here is to use a
run
block and return instead of break
Copy code
run {
    for (x in (2..n) {
        if (n % x == 0) {
            println(...)
            return@run
        }
    }
    ...
}
👍 1
h
Why is that?
n
yes
also I'm not sure but the iterator approach I don't think is correct
in particular, what happens if the break occurs on the last iteration?
I don't see how the iterator can distinguish those two cases
Sorry, you edited your comment, what do you mean "why is that"?
And yeah, I verified that the iterator approach is wrong
h
The edit was not intended. The question related to your statement about the incorrect iterator approach.
n
Copy code
fun main() {
    val iterator = (1..5).iterator()
    for(x in iterator){
        	if(x == 5){
            	println("x is 5")
            	break
        	}
    	}
    if (!iterator.hasNext()) {
        println("x was never 5")
    }
}
Try running this code
@diesieben07 may be interested
h
Thank you so much. And it looks even more elegant with run
n
the extra nesting level is a bit meh but yeah, overall I like run for these kinds of "odd" control flow exercises, it comes in handy quite often
👍 1
d
Ah, you are right Nir.
Thanks for correcting me 🙂
n
np 🙂