我有一些类似下面的Kotlin代码:

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

现在我得到以下警告:

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

我try 过给线程命名,并认为kotlin可能足够聪明来判断它,但我猜这可能不可能,因为返回标签可能不会在运行时解释.

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.

推荐答案

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

Thread {

    Thread Foo@ {

        return@Foo

    }.start()

}.start()

Kotlin相关问答推荐

了解Kotlin函数

在KMP中使用koin将来自Android的上下文注入到SQLDelight Driver中

Kotlin 协程:flatMapLatest 什么都不发出

如何使用 Mockk 模拟返回值类的 Kotlin 函数类型?

compareBy 如何使用布尔表达式在 kotlin 中工作

如何在 kotlin 中通过反射设置委托属性值?

来自类型参数的属性的自定义 getter

Kotlin 中的 Java Scanner 相当于什么?

在 Spring Framework 5.1 中注册具有相同名称的测试 bean

使用 Kotlin 创建新目录,Mkdir() 不起作用

在 Kotlin 中实现 (/inherit/~extend) 注解

ObjectAnimator.ofFloat 不能直接在kotlin中取Int作为参数

如何在Kotlin中使用ViewModelProviders

用Gradle Kotlin DSL构建源jar?

如果kotlin已经有了getter和setter,为什么在数据类中有componentN函数?

我应该使用Kotlin数据类作为JPA实体吗?

如何根据ArrayList的对象属性值从中获取最小/最大值?

将字符串转换为HashMap的最简单方法

使用 Moshi/Retrofit2 访问深度嵌套的 JSON 数组

将协程更新到 1.2.0 后构建失败:META-INF/atomicfu.kotlin_module