What is the difference between "var" and "val" in Kotlin?


In Kotlin, we can declare a variable using two different keywords: one is var and the other one is val. In this article, we will take an example and demonstrate how these declarations are different from each other.

Attributevarval
Declarationvar varName="hello World"val sName = "tutorialspoint.com"
ImmutabilityMutableImmutable
No. of times a variable can be assigned Can be assigned multiple times.Cannot be assigned multiple times.
Reassigned Can be reassignedCannot be reassigned

Example

In the following example, we will see how we can declare two different variables using "val" and "var". We will also see that the variable declared using 'var' can be changed, while the variable declared using 'val' cannot be reassigned as it will throw an error at runtime with the error message "Val cannot be reassigned."

val sName = "tutorialspoint";
var varName = "hello World"

fun main() {
   println("Example of val--->"+sName);
   println("Example of Var--->"+varName);

   // Variable declared by var is mutable
   varName = "new value";
   println("New value of the variable declared using Var: " +varName);
}

Output

It will generate the following output −

Example of val--->tutorialspoint
Example of Var--->hello World
New value of the variable declared using Var: new value

Example

Now, let's try to change the value of the variable declared using val

val sName = "tutorialspoint";
var varName = "hello World"

fun main() {
   println("Example of val--->"+sName);
   println("Example of Var--->"+varName);

   // Variable declared by val is not mutable
   sName = "new value";
   println("New value of the variable declared using Var: " +sName);
}

Output

It will throw an error at runtime −

main.kt:9:5: error: val cannot be reassigned
sName = "new value";
^

Updated on: 27-Oct-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements