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?
forEach
is 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
-
The syntax structure is different :
list.forEach
it 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 usesin
the keyword to traverse the elements in the collection. -
The return value is different :
list.forEach
there is no return value, it just applies the lambda expression to each element in the collection. Andfor (num in list)
returns each element during the traversal. You can use this return value to do other operations. -
Different readability :
list.forEach
the syntax structure is more concise, especially suitable for simple operations on collections. The syntax structure offor (num in list)
is more flexible, and you can write any logical processing in it.
2. Conclusion
- To simply iterate over the elements in a collection, use
list.forEach
- Use it when traversing a collection to do complex logic processing or when you need to return the traversed elements.
for (num in list)