- Functional Kotlin
- Mario Arias Rivu Chakraborty
- 289字
- 2021-06-24 19:15:27
What is immutability?
Functional programming, by its nature, is thread safe; immutability has a great role in making it thread safe. If you go by the dictionary definition, immutability means that something is unchangeable. So, as per the dictionary, an immutable variable is a variable that cannot change. Now, how can that be of any help to thread safety?
The following example shows a simple class, with no extra protective measures for thread safety:
class MutableObject { var mutableProperty:Int = 1 }
Just think of a situation when you're calling this class from multiple threads at the same time. There is no guarantee of integrity in this, right?
Now, imagine making mutableProperty immutable; the problem is partly solved, right?
However, if you think of immutability as creating a class and making all its variables read-only, then such a simplified explanation would not only be wrong, but would also be horrible. Actually, immutability is not about forbidding change, but about handling change. Instead of changing the underlying value of a property directly, create a new property and copy the value with applied changes. This applies to things such as the primitive data types in Kotlin and Java (or even in C). For instance, in the following example, when we're writing var y = x.capitalize(), the value of x remains unchanged, instead the x value is copied to y with applied changes:
fun main(args: Array<String>) { var x:String = "abc" var y = x.capitalize() println("x = $x, y = $y") }
Most of the primitive types operate in the same way; that is what is called immutability. Now, let's see how can we implement immutability in Kotlin and then, we will have a look at its advantages and disadvantages.
- Delphi程序設(shè)計基礎(chǔ):教程、實驗、習(xí)題
- 深入淺出Java虛擬機(jī):JVM原理與實戰(zhàn)
- Learning Flask Framework
- Python零基礎(chǔ)快樂學(xué)習(xí)之旅(K12實戰(zhàn)訓(xùn)練)
- Functional Programming in JavaScript
- Visual C++串口通信技術(shù)詳解(第2版)
- PostgreSQL Replication(Second Edition)
- FPGA Verilog開發(fā)實戰(zhàn)指南:基于Intel Cyclone IV(進(jìn)階篇)
- 動手學(xué)數(shù)據(jù)結(jié)構(gòu)與算法
- 零基礎(chǔ)學(xué)Kotlin之Android項目開發(fā)實戰(zhàn)
- 計算機(jī)應(yīng)用基礎(chǔ)(第二版)
- 快樂編程:青少年思維訓(xùn)練
- Java并發(fā)實現(xiàn)原理:JDK源碼剖析
- Learning Cocos2d-JS Game Development
- SAP HANA Starter