null pointer null pointer - 1 month ago 10
Android Question

The label does not denote a loop in forEach

I am continuing from a loop in Kotlin but I get the warning from the studio that the label does not denote a loop. Could someone tell me what's wrong in the syntax?

Here is the code segment

newRooms.forEach roomloop@ { wallRoom: WallRoom ->

val index = rooms.indexOf(wallRoom)

if(index!=-1)
{
val room = rooms[index] //get the corresponding room.
//check if the last session is same in the room.
if(wallRoom.topics.last().fetchSessions().last()==room.topics.last().fetchSessions().last())
{
continue@roomloop
}

Answer Source

The labeled lambda expression here is a function literal, not a loop.

You cannot break or continue the lambda expression here because it is independent from the for-loop.

public inline fun <T> Array<out T>.forEach(action: (T) -> Unit): Unit {
    for (element in this) action(element)
}

You may use return to return from the function.

return@roomloop

Note that the code segments below behave the same as the other one, both of them will print 123:

arrayOf(1, 2, 3).forEach label@ {
    print(it)
    return@label
}

label@ for (i in arrayOf(1, 2, 3)) {
    print(i)
    continue@label
}