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

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.

主站蜘蛛池模板: 巨鹿县| 磐安县| 玉环县| 太仓市| 富宁县| 桦甸市| 玉溪市| 涡阳县| 蓝田县| 绍兴市| 合阳县| 凤山市| 黄山市| 咸宁市| 荥经县| 黔东| 鄂托克旗| 玛曲县| 远安县| 昭苏县| 且末县| 伊通| 外汇| 沁源县| 五常市| 四平市| 治多县| 兴安县| 瓮安县| 临清市| 抚远县| 沙田区| 澄城县| 三都| 盐津县| 惠来县| 东丰县| 浦县| 昌平区| 乃东县| 讷河市|