Variables are containers for storing data values. In Kotlin, you declare a variable using either the var or val keyword.
var vs valvar (Variable): Use this when you expect the value of the variable to change later in the program. It creates a mutable variable.val (Value): Use this when you want the value to remain constant. Once assigned, a val cannot be reassigned. It creates an immutable variable (similar to final in Java or const in JavaScript).
fun main() {
var name = "John"
name = "Robert" // This is allowed because 'name' is a var
val birthYear = 1990
// birthYear = 1995 // ERROR: Val cannot be reassigned!
println(name)
println(birthYear)
}
Notice in the example above that we did not specify the type of data (like String or Integer). Kotlin is smart enough to understand that "John" is a text string and 1990 is a number. This feature is called Type Inference.
However, you can explicitly specify the type if you want to (or need to declare a variable without immediately assigning it a value).
fun main() {
val name: String = "John"
val age: Int = 30
}