Kotlin Variable

3. Kotlin Variable 3.1 Variable Declaration 3.2 Difference between val and var 3.3 Top level variable


Variable Declaration

A variable is a name or symbol that contains a value. We assign a value to a variable and that variable becomes reference to the assigned value.

In Kotlin, there are two keywords for declaring variables, val and var.

Example

fun main(args : Array<String>) {
    var x = "Tiger"
    val y = "Cow"
    println("$x  and $y")
}

In the above example, both var and val variables are of type string. It does not necessary to declare the variable type. But we can specify them, like -

fun main(args : Array<String>) {
    var x: String  = "Tiger"
    val y: String  = "Cow"
    println("$x and $y")
}
Output
Tiger and Cow


Difference between val and var

The var is equivalent to declaring a variable in Java, it is a mutable variable, which can be changed to another value by reassigning it. But, val is an immutable variable or read only variable which cannot be changed later in the program once the value is assigned. They can be assigned a value only once. This is similar to the final variable of Java.

We can reassign the value of variable declared using var, but we cannot reassign the value of variable declared using val.

Example

fun main(args : Array<String>) {    
	var x: String  = "Tiger"
    x = "Lion" //valid
    val y: String  = "Cow"
    y = "Dog" // error
    println("$x  and $y")
}

The above program returns the following error -

Error:(5,5) Kotlin: Val cannot be reassigned.

Top level variable

The variable used in function defined at the top level.

Example

fun main(args : Array<String>) {   
    var x: String  = "Tiger"
    fun wild() {
        println("$x is wild animal.")
    }
    wild()
}
Tiger is wild animal.







Read more articles