官术网_书友最值得收藏!

Compile time constants

So, how can we overcome this? How can we enforce immutability? The const val properties are here to help us. Just modify val myString with const val myString and you cannot implement the custom getter.

While val properties are read-only variables, const val on the other hand are compile time constants. You cannot assign the outcome (result) of a function to const val. Let's discuss some of the differences between val and const val:

  • The val properties are read-only variables, while const val are compile time constants
  • The val properties can have custom getters, but const val cannot
  • We can have val properties anywhere in our Kotlin code, inside functions, as a class member, anywhere, but const val has to be a top-level member of a class/object
  • You cannot write delegates for the const val properties
  • We can have the val property of any type, be it our custom class or any primitive data type, but only primitive data types and String are allowed with a const val property
  • We cannot have nullable data types with the const val properties; as a result, we cannot have null values for the const val properties either

As a result, the const val properties guarantee immutability of value, but have lesser flexibility and you are bound to use only primitive data types with const val, which cannot always serve our purposes.

Now, that I've used the word referential immutability quite a few times, let us now inspect what it means and how many types of immutability there are.

主站蜘蛛池模板: 敦化市| 贵港市| 普兰店市| 闸北区| 宣恩县| 新昌县| 仁布县| 东光县| 庐江县| 罗源县| 郑州市| 巴塘县| 城口县| 曲松县| 富源县| 和硕县| 丘北县| 丰顺县| 谷城县| 甘孜| 左云县| 大洼县| 深泽县| 聂拉木县| 台江县| 翁源县| 长泰县| 沁源县| 开阳县| 郎溪县| 金川县| 南乐县| 甘孜| 镇平县| 阳山县| 西青区| 衢州市| 和平县| 富顺县| 容城县| 乌兰浩特市|