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

  • Functional Kotlin
  • Mario Arias Rivu Chakraborty
  • 268字
  • 2021-06-24 19:15:28

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.

主站蜘蛛池模板: 沂水县| 扎赉特旗| 公安县| 南江县| 边坝县| 屏东县| 新兴县| 山东省| 中卫市| 青川县| 公主岭市| 屏东市| 乐清市| 英德市| 新和县| 伊川县| 镇康县| 镇沅| 集安市| 宜都市| 建宁县| 神农架林区| 济宁市| 株洲县| 杭锦旗| 米泉市| 通城县| 万全县| 永善县| 云龙县| 安国市| 南川市| 维西| 镇远县| 乌鲁木齐市| 道真| 巴林右旗| 荥阳市| 黎川县| 定南县| 紫金县|