Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
IOS上的InvalidMutabilityException使用Kotlin Multiplatform中的协程,具有可变变量_Kotlin_Kotlin Coroutines_Kotlin Multiplatform_Kotlin Native - Fatal编程技术网

IOS上的InvalidMutabilityException使用Kotlin Multiplatform中的协程,具有可变变量

IOS上的InvalidMutabilityException使用Kotlin Multiplatform中的协程,具有可变变量,kotlin,kotlin-coroutines,kotlin-multiplatform,kotlin-native,Kotlin,Kotlin Coroutines,Kotlin Multiplatform,Kotlin Native,我简化了错误,我只有这个类: class TestClass{ private var string = "Hello" fun testError() { string= "It Works" GlobalScope.launch(Dispatchers.Default) { string = "Doesn't work" } } }

我简化了错误,我只有这个类:

class TestClass{
    private var string = "Hello"

    fun testError() {
        string= "It Works"
        GlobalScope.launch(Dispatchers.Default) {
            string = "Doesn't work"
        }
    }
}
如果我在主线程(在IOS上)上启动TestClass().testError(),它将抛出InvalidMutabilityException(在-->string=“不工作”行)。所以我想,除了创建变量的线程外,在其他线程上更改变量可能不是一个好主意。所以我改为:

class TestClass{
    private var string = "Hello"

    fun testError() {
        string= "It Works"
        GlobalScope.launch(Dispatchers.Default) {
            withContext(Dispatchers.Main) { string = "Doesn't work" }
        }
    }
}
但它仍然抛出了一个错误:

kotlin.native.concurrent.InvalidMutabilityException:冻结的com.example.project的突变尝试。TestClass@fe10a8


顺便说一下。上述两个代码都在Android端工作,Kotlin/Native的线程模型与JVM不同<代码>测试类在lambda中捕获数据时被冻结。
字符串
赋值以静默方式捕获父级
TestClass
并将其冻结

见下文:


凯文·加里根的精彩演讲!帮了很多忙!谢谢