I have a class like this:
class MyClass {
private val myLock = ReentrantLock()
...
}
In java I would make this field final to provide memory guarantees: https://stackoverflow.com/a/27254652/2674303
Does val
provides the same guarantees ?
Yes, at least on Kotlin/JVM. For other platforms, probably not.
While I couldn't find authoritative documentation on this (The Kotlin/JVM spec still hasn't been written), a private val
declared in the way your example does, compiles to a final
field in bytecode. You can see this by inspecting the .class file. It is unlikely that they will change this to generate a non-final
field in the future, because as you pointed out, final
fields have certain guarantees, and removing final
will be a breaking change.
Of course, if the val
doesn't have a backing field, like val x get() = 1
, then no field is generated.