- Hands-On Design Patterns with Kotlin
- Alexey Soshin
- 87字
- 2021-06-25 20:49:23
val versus var
In Java, variables can be declared final. Final variables can be assigned only once:
final String s = "Hi";
s = "Bye"; // Doesn't work
Kotlin urges you to use immutable data as much as possible. Final variables in Kotlin are simply val:
val s = "Hi"
s = "Bye" // Doesn't work
If you do have a case in which you would like to reassign a variable, use var instead:
var s = "Hi"
s = "Bye" // Works now
推薦閱讀