I see yet another function in Kotlin/Native, that does not exist in the Kotlin JVM or JS. What does it?
From Kotlin native's Concurrency docs
Freezing is a runtime operation making given object subgraph immutable, by modifying the object header so that future mutation attempts lead to throwing an InvalidMutabilityException. It is deep, so if an object has a pointer to another objects - transitive closure of such objects will be frozen. Freezing is the one way transformation, frozen objects cannot be unfrozen. Frozen objects have a nice property that due to their immutability, they can be freely shared between multiple workers/threads not breaking the "mutable XOR shared" invariant.
Sharing a more recent and easier explanation from Kotlin Multiplatform Mobile docs here:
The Native runtime adds an extension function freeze() to all classes. Calling freeze() will freeze an object, and everything referenced by the object, recursively. Eg:
data class MoreData(val strData: String, var width: Float)
data class SomeData(val moreData: MoreData, var count: Int)
//...
val sd = SomeData(MoreData("abc", 10.0), 0)
sd.freeze()
- freeze() is a one-way operation. You can't unfreeze something.
- freeze() is not available in shared Kotlin code, but several libraries provide expect and actual declarations for using it in shared code. However, if you're using a concurrency library, like kotlinx.coroutines, it will likely freeze data that crosses thread boundaries automatically.
- freeze is not unique to Kotlin. You can also find it in Ruby and JavaScript.
© 2022 - 2024 — McMap. All rights reserved.