Skip to main content

Variables

Basic variable declarations in Kotlin come in the form of
{mutability indicator} {variable name} (optional) {: variable type}

Prefix

Semi-colons are optional in Kotlin and should be omitted in all cases that don't require them.
Do not worry about the situations in which they are required until you encounter an error.

Mutability Indicator

This can either be val or var.
val refers to a immutable variable (cannot be re-assigned).

// Usage of non re-assignable variables
val aNum = 5
val aNotherNum = 5 + 5

// This is an ERROR since aNum is a val
aNum = 10

var refers to a traditional Java mutable variable.

fun main() {
//sampleStart
// Usage of re-assignable variables
var aNum = 5
aNum += 5
aNum = 0
//sampleEnd
println("The variable aNum's value is ${aNum}")
}
Other languages

In java val is equivalent to marking a variable as final although this is rarely done with local variables.
var is unnecessary in java as all non-final variables are mutable.

Typing Variables

As mentioned in our Kotlin Intro Kotlin has type inference.
This means that Kotlin will allow the developer to omit the type of a variable if the compiler is able to infer it.
What does this look like in practice?

// This is a constant variable with it's type inferred
val aString = "I am a String"

// This is a constant variable with it's type inferred even though it is not hard coded
val aUpperCaseString = aString.toUpperCase()

// This is a constant variable with it's type explicitly set
val aNum: Int = 2

// This is an ERROR as the compiler cannot infer the variable type since it is not assigned a value
val aBool

When you do not assign a value to a variable, it's type cannot be inferred and thus is an error if you omit the type.

Opinion -
In general when coding in large software codebases it is good to provide types in certain times when it is not necessary to improve readability and code searchability.