In this tutorial, you shall learn about Variables in Kotlin, how to declare a variable, how to specify a type for the variable, and how to initialize a variable, with examples.

Kotlin Variables

Kotlin Variables are used to store values. The data type of the variable decides the type of values that can be stored in it.

Declare a Variable

To declare a variable, we may use the keyword var or val. var is used to declare a mutable variable. val is sued to declare an immutable variable.

The syntax to declare a variable is

var variableName: DataType
val variableName: DataType

Examples

var x: Int
val y: Int

x and y are variable names. Int is the datatype.

ADVERTISEMENT

Initialize a Variable

To initialize a variable, use assignment operator = and assign the value to variable.

The syntax to assign a variable is

variableName = value

Example

var x: Int
x = 10

Declare and Initialize a variable in a single statement

We can also combine both the declaration and initialization. Declaration and initialization of a variable can be done in a single statement.

var x: Int = 10

Since Kotlin can infer the datatype from the value assigned, declaring the datatype would become optional.

var x = 10

var and val

var keyword declares a mutable variable. We can modify the value stored in variable.

val keyword declares an immutable variable. Once the variable is initialized, we cannot modify the value stored in the variable.

Examples

In the following example, we declare a variable x using var keyword and initialize it to a value of 10. We then modify its value to 20.

Main.kt

fun main(args: Array<String>) {
    var x = 10
    x = 20
    print("x is $x")
}

Output

x is 20

In the following example, we declare a variable x using val keyword and initialize it to a value of 10. We then try to modify its value to 20. Since x is immutable, build error occurs.

Main.kt

fun main(args: Array<String>) {
    val x = 10
    x = 20
    print("x is $x")
}

Output

/Users/tutorialkart/IdeaProjects/KotlinTutorial/src/Main.kt:3:5
Kotlin: Val cannot be reassigned

Conclusion

In this Kotlin Tutorial, we learned what a Kotlin Variable is, how to declare and initialize a variable, with the help of examples.