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

Immutability

Immutability is the opposite of mutation. Mutation is where we modify the state of an object. Mutation is error-prone and makes debugging difficult. Kotlin emphasizes immutability with val, which makes a variable immutable. Its collection types are also immutable by default. Once the val or collection is initialized, it is guaranteed to hold the same value. Immutability makes code easier to write and use and the internal state of the application will be more consistent.

Let's consider the following code sample:

object ImmutabilityTest {
@JvmStatic
fun main(args: Array<String>) {
val msg = "Hello"
msg = "hi"
println(msg)
}
}

In the preceding code, we created a immutable variable, msg, assigned a value. We then try to change its value.

If we compile this code, it gives us a compilation error that the value of msg cannot be changed:

[INFO] Changes detected - recompiling the module!
[INFO] Compiling 2 source files to ..\Intermixing Java and Kotlin\myJavaApp\target\classes
[INFO]
[INFO] --- kotlin-maven-plugin:1.2.41:compile (compile) @ myJavaApp ---
[ERROR] ..\Intermixing Java and Kotlin\myJavaApp\src\main\java\ImmutabilityTest.kt: (5, 9) Val cannot be reassigned

Consider the following example as well:

object ImmutabilityTest {
@JvmStatic
fun main(args: Array<String>) {
val msg: String
msg = "Good Morning"
msg = "Good Evening"

println(msg)
}
}

In the preceding code, we created a immutable variable, msg, which is of the String type. Note that we declared the type explicitly here and varied the initialization of msg. When we are varying the initialization, we have to declare the type explicitly. We then try to change its value. 

If we compile this code, it also gives us a compilation error that the value of msg cannot be changed:

[INFO] Changes detected - recompiling the module!
[INFO] Compiling 2 source files to ..\Intermixing Java and Kotlin\myJavaApp\target\classes
[INFO]
[INFO] --- kotlin-maven-plugin:1.2.41:compile (compile) @ myJavaApp ---
[ERROR] ..\Intermixing Java and Kotlin\myJavaApp\src\main\java\ImmutabilityTest.kt: (6, 9) Val cannot be reassigned
主站蜘蛛池模板: 大港区| 金沙县| 朔州市| 海盐县| 都江堰市| 克东县| 黑水县| 曲阳县| 和硕县| 顺昌县| 固安县| 铅山县| 时尚| 余干县| 革吉县| 松原市| 白城市| 泰州市| 福安市| 洛宁县| 德保县| 仪陇县| 邛崃市| 田林县| 桐庐县| 锡林浩特市| 舞阳县| 汕尾市| 建瓯市| 衡阳县| 池州市| 娄烦县| 美姑县| 平度市| 石台县| 怀来县| 北海市| 九台市| 库车县| 巴林右旗| 泽普县|