我试过这样的方法:

private volatile var instanceState: InstanceState = InstanceState.starts

Error:  'Expected member declaration'

就像这样:

private volatile var instanceState: InstanceState = InstanceState.starts

Error:  'Property getter or setter expected'

Volatile not supported on Kotlin ?

推荐答案

可以使用@Volatile注释将特性标记为volatile:

@Volatile var name:String = "stack"

生成的字段声明等同于Java的:

private volatile java.lang.String name;

根据这@Volatile份文件:

Marks the JVM backing field of the annotated property as volatile, meaning that writes to this field are immediately made visible to other threads.

Kotlin相关问答推荐

调用即发即忘方法--哪个作用域?

如何编写带有依赖项的自定义Kotlin串行化程序?

如何进行基于lambda/谓词的两个列表的交集?

捕捉异常是Kotlin协程中的反模式吗?

如何使用Kotlinx.LocalDateTime获取重置时间为00:00的当前日期?

为什么在jacksonObjectMapper上将DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES设置为false无效?

Kotlin SIZE_BYTES

mutableStateOf 在 Jetpack Compose 中不记住 API 的情况下保持重组后的值

奇怪的 cotlin check Not Null 参数错误

如何在 Kotlin for Android 上使用setTextColor(hexaValue),

如何有效地填充 Gradle Kotlin DSL 中的额外属性?

如何在调试中修复 ClassNotFoundException: kotlinx.coroutines.debug.AgentPremain?

在协程中等待侦听器内的数据

如何在使用 Gradle 的 AppEngine 项目中使用 Kotlin

什么是开放式property?为什么我不能将其设置器设为private私有?

如何使用kotlin中的反射查找包中的所有类

Gradle:无法连接到 Windows 上的 Kotlin 守护程序

在android java类中使用Kotlin扩展

在 Kotlin 中声明 Byte 会出现编译时错误The integer literal does not conform to the expected type Byte

带有注释为@RegisterExtension的字段的 JUnit 5 测试在 Kotlin 中不起作用