Local variables

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, the compiler must be sure that  the variable is properly initialized in the scope. This example will compile because the compiler knows that the variable is initialized and has not been used before initialization:

 val bar: String
if (true) {
bar = "Foo"
}
else {
bar = "Bar"
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.34.146