- 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.
- Designing Machine Learning Systems with Python
- Computer Vision for the Web
- PostgreSQL Cookbook
- Unity Virtual Reality Projects
- Getting Started with CreateJS
- Wireshark Network Security
- Learning Python by Building Games
- Python機器學習算法: 原理、實現與案例
- Unity 2018 Shaders and Effects Cookbook
- Mastering Elixir
- 深度學習程序設計實戰
- 精通Spring:Java Web開發與Spring Boot高級功能
- Python編程快速上手2
- Java高級程序設計
- JavaWeb從入門到精通(視頻實戰版)