What is .freeze() in Kotlin/Native?
Asked Answered
A

2

7

I see yet another function in Kotlin/Native, that does not exist in the Kotlin JVM or JS. What does it?

Aerodynamics answered 3/9, 2018 at 9:32 Comment(1)
Looks like a native function from a search in the source code, related to memory management? Not sure, but it looks like itHurried
M
8

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.

Margerymarget answered 3/9, 2018 at 9:35 Comment(0)
P
2

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.
Piatt answered 19/6, 2021 at 1:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.