Kotlin Variables

Kotlin Variables

In Kotlin, we can define a variable using var keyword.

var x = "apple"

where

  • var is the keyword
  • x is the variable name
  • = is the assignment operator
  • "apple" is the value

If we do not initialise the variable, we have to specify the data type, as shown in the following.

var x: String

Once a variable is defined, or initialled, we can reassign another value of the same datatype.

var x = "apple"
x = "banana"

Constants

If we do not want the value to be changed, then we can declare the variable using val keyword. val keyword makes the variable immutable.

val pi = 3.14

Once a value is assigned, we cannot reassign a new value to the variable.