In Java, you start a variable declaration with a type. This wouldn’t work for Kotlin, because it lets you omit the types from many variable declarations. Thus in Kotlin you start with a keyword, and you may (or may not) put the type after the variable name.
Let’s declare two variables:
val question = “The Ultimate Question of Life, the Universe, and Everything”
val answer = 42
This example omits the type declarations, but you can also specify the type explicitly if you want to:
val answer: Int = 42
Just as with expression-body functions, if you don’t specify the type, the compiler analyzes the initializer expression and uses its type as the variable type. In this case, the initializer, 42, has Int type, so the variable will have the same type.
If you use a floating-point constant, the variable will have the type Double:
val yearsToCompute = 7.5e6
MUTABLE AND IMMUTABLE VARIABLES
- val (from value)—Immutable reference. A variable declared with val can’t be reassigned after it’s initialized. It corresponds to a final variable in Java
- var (from variable)—Mutable reference. The value of such a variable can be changed. This declaration corresponds to a regular (non-final) Java variable
Even though the var keyword allows a variable to change its value, its type is fixed. For example, this code doesn’t compile:
var answer = 42
answer = “no answer”