Open In App

Difference between var and val in Kotlin

Improve
Improve
Like Article
Like
Save
Share
Report

var and val are both used to declare variables in Kotlin language. However, there are some key differences between them:

VAR(Variable)

It is a general variable. The value of a variable that is declared using var can be changed anytime throughout the program. var is also called mutable and non-final variable, as there value can be changed anytime.
Example:




fun main()
 {
   var marks = 10
   println("Previous marks is " + marks)
   marks = 30
   println("New marks " + marks)
 }


Output :

Previous marks is 10
New marks 30

VAL(Value)

The object stored using val cannot be changed, it cannot be reassigned, it is just like the final keyword in java. val is immutable. Once assigned the val becomes read-only, however, the properties of a val object could be changed, but the object itself is read-only.

Example 1:




fun main()
{
    val marks = 10 
    println("Previous marks is " + marks)
    marks = 30 
    println("new marks " + marks)
}


Output:

Val cannot be reassigned

Example 2:




// Changing values of val object
fun main()
{
    val book = Book("Java", 1000)
    println(book)
    book.name = "Kotlin" 
    println(book)
}
data class Book(var name : String = "",
                var price : Int = 0)


output:

Book(name=Java, price=1000)
Book(name=Kotlin, price=1000)


Last Updated : 03 Jun, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads