Difference between var and val in Kotlin

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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:



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Val cannot be reassigned

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)

chevron_right


output:

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.