- Kotlin for Enterprise Applications using Java EE
- Raghavendra Rao K
- 313字
- 2021-06-10 18:49:24
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
- Mastering Concurrency Programming with Java 8
- Spring Boot開發(fā)與測試實(shí)戰(zhàn)
- Java編程指南:基礎(chǔ)知識、類庫應(yīng)用及案例設(shè)計
- Django Design Patterns and Best Practices
- Java游戲服務(wù)器架構(gòu)實(shí)戰(zhàn)
- Drupal 8 Configuration Management
- Python數(shù)據(jù)結(jié)構(gòu)與算法(視頻教學(xué)版)
- Statistical Application Development with R and Python(Second Edition)
- Isomorphic Go
- 透視C#核心技術(shù):系統(tǒng)架構(gòu)及移動端開發(fā)
- 小學(xué)生C++趣味編程從入門到精通
- Learning Apache Thrift
- 微信公眾平臺開發(fā)最佳實(shí)踐
- Implementing Splunk(Second Edition)
- 生成藝術(shù):Processing視覺創(chuàng)意入門