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

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.

主站蜘蛛池模板: 谢通门县| 寿宁县| 简阳市| 南丰县| 贺州市| 临高县| 南昌市| 乌海市| 瑞昌市| 庆云县| 乌什县| 新昌县| 西盟| 漳浦县| 阿拉善左旗| 谷城县| 女性| 临颍县| 齐齐哈尔市| 山阴县| 白水县| 涡阳县| 宝兴县| 右玉县| 云梦县| 泾川县| 缙云县| 资兴市| 河东区| 都昌县| 南乐县| 泸水县| 永顺县| 平昌县| 香格里拉县| 龙游县| 乐安县| 金寨县| 睢宁县| 偃师市| 无棣县|