Interface definition of public get, private set property

Hi,

I am new to Kotlin - just started learning the language, though I am familiar with both Java and C#. I am in the earlty stages of converting a C# program to Kotlin, and one of the first actions I needed to perform was to define and interface with a property with a public GET, but private SET. (C# definition of public and private - private being restricted to the class, not the file.)

I eventually discovered that the official mechanism to achieve this is to declare the property as VAL in the interface, and on implementing it override using VAR with private set.

First can I confirm that this is indeed the mechanism I should be using.

Second, assuming the mechanism described is what I should be using, then I was under the understanding that VAL meant read-only, i.e. immutable. Clearly that is not the case with the implementation above. Why does it matter? Immutable properties are, by definition, thread-safe. How do I know when examining an interface whether a property marked as VAL is actually thread-safe?

val just means readonly, not immutable. There is no way to define a property as immutable in kotlin. vals are not thread safe. If you want thread safety, the only way to ensure it is to use a Mutex.
The interface mechanism is indeed correct, or you could maybe forgo the interface and just use the class directly.

Different languages, different definitions of similar concepts. In c# ‘readonly’ is thread-safe. However, delving further, in Kotlin VAL can define a function, so whilst the definition may not change, its actual value can. Result - VAL is not thread safe.

Thanks.

1 Like