Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin nested threads - "there is more than one label with such a name in this scope"

I have some kotlin code similar to this:

Thread {
    ...
    Thread {
        ...
        return@Thread
        ...
    }.start()
    ...
}.start()

Now I get the following warning:

enter image description here

I understand that kotlin is confused as to which Thread I want to return at this point, whether it's the outer or the inner thread. But I'm not sure how to tell it and Android Studio doesn't help much either, as it only suggests editing the options for this warning:

enter image description here

I have tried naming the thread and thought maybe kotlin is smart enough to check for that, but I guess this might not be possible, because the return label is probably not interpreted on runtime.

I realize that I can just export the inner thread into a function and thereby have the threads not interfere with each other, like this:

Thread {
    ...
    startInnerThread()
    ...
}.start()

fun startInnerThread() {
    Thread {
        ...
        return@Thread
        ...
    }.start()
}

But I would like to know if it's somehow possible to change the label @Thread for one of them instead.

like image 926
Benjamin Basmaci Avatar asked Jan 16 '20 17:01

Benjamin Basmaci


1 Answers

Yea, you can do this by labelling the function to return from like so:

Thread {

    Thread Foo@ {

        return@Foo

    }.start()

}.start()
like image 131
Thomas Cook Avatar answered Oct 30 '22 17:10

Thomas Cook