The val keyword

The val keyword is a read-only variable that is used to declare an immutable variable. Immutable means that once the variable is assigned, it will remain the same until the end of the application's life:

val age = 25 

In the preceding code line, val is a keyword, age is a variable name, and 25 is an integer value assigned.

val is the same as var; the variable type is dependent on the value assigned to the variable.

The read-only feature is actually one of the safety features provided by Kotlin.

Once the variable is declared, it is not possible to update it under any circumstances. This feature becomes more important when we are writing a complex application or a program of scientific calculations:

val pi = 3.14159

Knowing that the value of pi is constant, it would be a good practice to use val instead of var to make sure that the value remains constant and cannot be changed accidentally. Once declared as val, try to re-assign any other value to pi as follows:

pi = 123.345 // The result: Compiler will throw an error: "val cannot re-assign".

It is necessary that we declare different variables with the val keyword:

fun main(args: Array<String>) {
val name = "Herry" // String variable
val PI = 3.1415 // Double variable
val programmingLanguage = "Kotlin"
programmingLanguage = "Java" // Error: val cannot be reassigned
println("Name is $name and my favorite programming language is $programmingLanguage")
}

..................Content has been hidden....................

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