Difference Between val and var in Kotlin

Difference Between val and var in Kotlin

In this article, we are going to learn the difference between "val" and "var" keyword. In kotlin Programming language we used "val" and "var" for declaring variables. Kotlin Programming Language supports mutable and immutable variables. In Kotlin Programming Langauge it is recommended to use immutable variables are preferred whenever possible. Now again What is immutable and mutable? As per English dictionary, mutable means liable to change.
Ok, now we know what is mutable and immutable. Next question, Which one is mutable and which one is immutable. For this let's check the definitions for var and val.

var

var it is the short form of the variable. Variable means it is going to vary. So we can say object stored in a var could be changed.
Following are the example of a variable.

Code

fun main(args:Array<String>)
{
    
    /*
    * Mutable Variables
    * */
    var MyAge=120
    var MyName="Mayank Sanghvi"

    /*
    * Defiantly my age is not 120 re-assign it.
    * */
    MyAge=18
    MyName="Mayank"
    /*
    * Now, I am lying about my age. But you can assign mutable variables multiple times.
    * */
}

In the above example, we declare two variables "MyAge" and "MyName". Next is Val

val

val is the short form of Value. If var is mutable it means val is immutable. You cannot change the object stored in a val. You can declare a val without initializing it. Once the val variable is initialized you can't change it. In other words, you can say val are read-only variables or Kotlin Programming Language constant.
Following are some example for val.

Code

fun main(args:Array<String>)
{
    /*
    * Immutable Variables
    * */
    val EarthGravity=9.8
    val PI=3.14159

    println("Constant Variable 1 Value: $EarthGravity")
    println("Constant Variable 2 Value: "+PI)

    /*
    * Below line throws error
    * Error:(19, 5) Kotlin: Val cannot be reassigned
    * */
    EarthGravity=0
}

In the above example, we created two immutable variables or val. First one is EarthGravity and second one is PI. Both are constants. If you are using it in your code you don't want anyone to change the value for both the constants.
If you love physics like me then Just imagine in your mind what happens if someone overwrites the EarthGravity to 0. I am flying without any wings ;-). Ok, let's answer the main question for this article.
Question: What is the difference between var and val in Kotlin Programming Language?
Answer: Var is mutable variables and Val are immutable variables. You can change the value stored in a Var variable. But value stored in a Val is read-only.
Following is the free Kotlin Programming Language Tutorial.

 Kotlin Tutorial Beginner Guide

0 Comments
Leave A Comment

Please login to post your valuable comments.

Join the newsletter

Get the latest vLemonn news first

share