-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating
Kotlin Quick Start Guide
By :
Local variables can be declared in two ways: first, with the val keyword, then they are immutable (the variable cannot be reassigned). If you are coming from Java, val would be equal to variables declared with a final keyword.
Secondly, you can declare a local variable with a var keyword; then it is considered mutable and the value can be reassigned after a declaration.
The following command demonstrates that it will not compile, because the bar local variable cannot be reassigned:
fun immutable() {
val bar: String = "Kotlin"
bar = "Kotlin is awesome" // compiler error
}And, when declared with var, the compiler allows a local variable to be reassigned:
fun mutable() {
var bar: String = "Kotlin"
bar = "Kotlin is awesome"
}You should favor immutable variables. The compiler will give you a warning if you use a mutable variable but only assign it once.
Whether you declare a variable as mutable or immutable, it has to have a value when it is declared, or, if it doesn’t have a value...