0

I am writing a Kotlin program and I want to skip an iteration of the loop. I know the continue keyword, that jumps to the next interation, but is there a way to elegantly jump to the second next iteration, skipping the next iteration? I would imagine the code to look like this:

for(i in 0 until 10){
    if(i == 5){
        skip
    }
    println(i)
}

with the result being this:

0
1
2
3
4
7
8
9

PS: I know how I could do it other ways, but I am asking if there is a very easy or kotlin-native way of doing this.

2
  • How is skip more elegant than continue aside from using a different word? Commented Jul 7, 2018 at 18:06
  • 2
    continue goes to the next iteration. skip would skip the next iteration and continue at the iteration after the next Commented Jul 7, 2018 at 18:07

1 Answer 1

3

If you are interested in a for loop, then you can simplify it by using a range and a predicate that removes some values from the loop:

(0..9).filter { !(it in 5..6) }.forEach { println(it) }

here !(it in 5..6) is the predicate but you can build your own.

Sign up to request clarification or add additional context in comments.

1 Comment

I always prefer ! before a parenthesis when possible because I think it's more readable. It's a matter of style.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.