kotlin loop

Recently, when I was writing a project, I encountered a problem about kotlin jumping out of loops . Due to project reasons, let’s just take the following simple example as a demo.

1. Questions

First, let’s look at a normal function to jump out of a loop. Everyone knows it, so I’ll just post the code:

val list = listOf(1, 2, 3, 4, 5)
for (num in list) {
    
    
    if (count == 3) {
    
    
        break // 退出循环
    }
    // 打印 1和2
    println(num)
}

During the actual development process, I used the list.forEach function

// label@标签
list.forEach label@{
    
    
    if (it == 3) {
    
    
        // 在这里return之后,实际上并没有跳出循环
        return@label
    }
    // 打印 1 2 4 5
    println("label:$it")
}

In the above example, after calling return@label, the loop does not actually break out. What we want is to break out of the loop when the it value is 3, print 1, 2, actually print 1, 2, 4, 5, and continue. Same

for (i in list) {
    
    
    if (i == 3) {
    
    
        continue
    }
    println("continue:$i")
}

So why is the forEach function not available to break out of the loop?

forEachis a higher-order function that takes a lambda expression as argument and applies it to each element in the collection. Because it just traverses each elementforEach in the collection , it does not return a value .

Finally, let’s talk about the difference between list.forEach and for loop

  1. The syntax structure is different : list.forEachit is a higher-order function that receives a lambda expression as a parameter. Instead, for (num in list)is an iterator-based syntax structure that uses inthe keyword to traverse the elements in the collection.

  2. The return value is different : list.forEachthere is no return value, it just applies the lambda expression to each element in the collection. And for (num in list)returns each element during the traversal. You can use this return value to do other operations.

  3. Different readability : list.forEachthe syntax structure is more concise, especially suitable for simple operations on collections. The syntax structure of for (num in list)is more flexible, and you can write any logical processing in it.

2. Conclusion

  1. To simply iterate over the elements in a collection, uselist.forEach
  2. Use it when traversing a collection to do complex logic processing or when you need to return the traversed elements.for (num in list)

Guess you like

Origin blog.csdn.net/flytosky21/article/details/130030469