Kotlin: Val and Var in Kotlin

Kotlin Programming

Question or issue of Kotlin Programming:

What is the difference between var and val in Kotlin?

I have gone through this link:

KotlinLang: Properties and Fields

As stated on this link:

But just before there is an example which uses a setter.

fun copyAddress(address: Address): Address {
    val result = Address() // there's no 'new' keyword in Kotlin
    result.name = address.name // accessors are called
    result.street = address.street
    // ...
    return result
}

What is the exact difference between var and val?

Why do we need both?

This is not a duplicate of Variables in Kotlin, differences with Java: ‘var’ vs. ‘val’? as I am asking about the doubt related to the particular example in the documentation and not just in general.

How to solve this issue?

Solution no. 1:

In your code result is not changing, its var properties are changing. Refer comments below:

fun copyAddress(address: Address): Address {
    val result = Address() // result is read only
    result.name = address.name // but not their properties.
    result.street = address.street
    // ...
    return result
}

val is same as the final modifier in java. As you should probably know that we can not assign to a final variable again but can change its properties.

Solution no. 2:

val and var both are used to declare a variable.


var is like general variable and it’s known as a mutable variable in kotlin and can be assigned multiple times.
val is like Final variable and it’s known as immutable in kotlin and can be initialized only single time.

For more information what is val and var please see below link


http://blog.danlew.net/2017/05/30/mutable-vals-in-kotlin/

Solution no. 3:

variables defined with var are mutable(Read and Write)

variables defined with val are immutable(Read only)

Kotlin can remove findViewById and reduce code for setOnClickListener in android studio. For full reference: Kotlin awesome features

value of mutable variables can be changed at anytime, while you can not change value of immutable variables.

where should I use var and where val ?

use var where value is changing frequently. For example while getting location of android device

var integerVariable : Int? = null

use val where there is no change in value in whole class. For example you want set textview or button’s text programmatically.

val stringVariables : String = "Button's Constant or final Text"

Solution no. 4:

val use to declare final variable. Characteristics of val variables

  1. Must be initialized
  2. value can not be changed or reassign
    enter image description here

var is as a general variable

  1. We can initialize later by using lateinit modifier

    [lateinit also use for global variable
    we can not use it for local variable]

  2. value can be changed or reassign but not in global scope

enter image description here

val in kotlin is like final keyword in java

Solution no. 5:

Simply,
var (mutable) and val (immutable values like in Java (final modifier))

var x:Int=3
x *= x

//gives compilation error (val cannot be re-assigned)
val y: Int = 6
y*=y

Solution no. 6:

val is immutable and var is mutable in Kotlin.

Solution no. 7:

Simply think Val like final Variable in java

Solution no. 8:

+----------------+-----------------------------+---------------------------+
|                |             val             |            var            |
+----------------+-----------------------------+---------------------------+
| Reference type | Immutable(once initialized  | Mutable(can able to change|
|                | can't be reassigned)        | value)                    |
+----------------+-----------------------------+---------------------------+
| Example        | val n = 20                  | var n = 20                |
+----------------+-----------------------------+---------------------------+
| In Java        | final int n = 20;           | int n = 20;               |
+----------------+-----------------------------+---------------------------+

Reference

Solution no. 9:

If we declare variable using val then it will be read-only variable. We cannot change it’s value. It’s like final variable of Java. It’s immutable.

But if we declare variable using var then it will be a variable which we can read or write. We can change it’s value. It’s mutable.

data class Name(val firstName: String, var lastName: String)

fun printName(name: Name): Name {
    val myName = Name("Avijit", "Karmakar") // myName variable is read only
    // firstName variable is read-only. 
    //You will get a compile time error. Val cannot be reassigned.
    myName.firstName = myName.firstName
    // lastName variable can be read and write as it's a var.
    myName.lastName = myName.lastName
    return myName
}

val cannot be initialized lately by the keyword lateinit but non-primitive var can be initialized lately by the keyword lateinit.

Solution no. 10:

You can easily think it as:

var is used for setter (value will change).

val is used for getter (read-only, value won’t change).

Solution no. 11:


In Kotlin val is a read-only property and it can be accessed by a getter only. val is immutable.

val example :

val piNumber: Double = 3.1415926 get() = field 


However, var is a read-and-write property, so it can be accessed not only by a getter but a setter as well. var is mutable.

var example :

var gravity: Double = 9.8 get() = field set(value) { field = value } 

If you try to change an immutable val, IDE will show you error :

fun main() { piNumber = 3.14 // ERROR println(piNumber) } // RESULT: Val cannot be reassigned 

But a mutable var can be changed :

fun main() { gravity = 0.0 println(gravity) } // RESULT: 0.0 

Hope this helps.

Solution no. 12:

Basically

  • var = variable, so it can change
  • val = value, so it can not change.

Solution no. 13:

val property is similar to final property in Java. You are allowed to assign it a value only for one time. When you try to reassign it with a value for second time you will get a compilation error. Whereas var property is mutable which you are free to reassign it when you wish and for any times you want.

Solution no. 14:

Value to val variable can be assigned only once.

val address = Address("Bangalore","India") address = Address("Delhi","India") // Error, Reassigning is not possible with val 

Though you can’t reassign the value but you can certainly modify the properties of the object.

//Given that city and country are not val address.setCity("Delhi") address.setCountry("India") 

That means you can’t change the object reference to which the variable is pointing but the underlying properties of that variable can be changed.

Value to var variable can be reassigned as many times as you want.

var address = Address("Bangalore","India") address = Address("Delhi","India") // No Error , Reassigning possible. 

Obviously, It’s underlying properties can be changed as long as they are not declared val.

//Given that city and country are not val address.setCity("Delhi") address.setCountry("India") 

Solution no. 15:

Do you need to change a variable or set it permanently?

  • A good example if it is something like val pi5places = 3.14159 you would set it as val. Is there a possibility that you need to change that variable now or later, then you would set it as var.

  • For example : The color of a car, can be var colorCar = green. Later you can change that colorCar = blue, where as a val, you can not.

  • Responses here regarding mutable and immutable is fine, but may be scary if these terms are not well known or just getting into learning how to program.

Solution no. 16:

Two ways to create variable in KOTLIN VAL and VAR

1.VAL stores constant values. Also called Final Variable

2.VAR stores Changeable Values

Click here for example

Solution no. 17:

Comparing val to a final is wrong!

vars are mutable vals are read only; Yes val cannot be reassigned just like final variables from Java but they can return a different value over time, so saying that they are immutable is kind of wrong;

Consider the following

var a = 10 a = 11 //Works as expected 
val b = 10 b = 11 //Cannot Reassign, as expected 

So for so Good!

Now consider the following for vals

val d get() = System.currentTimeMillis() println(d) //Wait a millisecond println(d) //Surprise!, the value of d will be different both times 

Hence, vars can correspond to nonfinal variables from Java, but val aren’t exactly final variables either;

Although there are const in kotlin which can be like final, as they are compile time constants and don’t have a custom getter, but they only work on primitives

Solution no. 18:

val is immutable, final, the first assigned value cannot be changed.

val name:String = "andy" name = "thomas" //Error: Val cannot be reassigned 

var is mutable, reassignable, you can change the value over and over.

val a:Int = 1 var b:Int = 1 println("${a + b}") // output 2 b = 4 println("${a + b}") // output 5 


I think the easiest way to remember it :
val = variable final
var = variable reassignable, or the opposite of val.

Solution no. 19:

val like constant variable, itself cannot be changed, only can be read, but the properties of a val can be modified;
var just like mutant variable in other programming languages.

Solution no. 20:

Both, val and var can be used for declaring variables (local and class properties).

Local variables:

  1. val declares read-only variables that can only be assigned once, but cannot be reassigned.

Example:

val readonlyString = “hello”
readonlyString = “c u” // Not allowed for `val`
  1. var declares reassignable variables as you know them from Java (the keyword will be introduced in Java 10, “local variable type inference”).

Example:

var reasignableString = “hello”
reasignableString = “c u” // OK

It is always preferable to use val. Try to avoid var as often as possible!

Class properties:

Both keywords are also used in order to define properties inside classes. As an example, have a look at the following data class:

data class Person (val name: String, var age: Int)

The Person contains two fields, one of which is readonly (name). The age, on the other hand, may be reassigned after class instantiation, via the provided setter. Note that name won’t have a corresponding setter method.

Hope this helps!