What is the difference between var and val in Kotlin?

Viewed 172999

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:

The full syntax of a read-only property declaration differs from a mutable one in two ways: it starts with val instead of var and does not allow a setter.

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.

41 Answers

Basically

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

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.

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

var is like a general variable and can be assigned multiple times and is known as the mutable variable in Kotlin. Whereas val is a constant variable and can not be assigned multiple times and can be Initialized only single time and is known as the immutable variable in Kotlin.

Val: Assigned once (Read only)

Var: Mutable

example : define a variable to store userId value:

val userId = 1

if we are trying to change the variable userId you will get Error message

userId = 2
error: val cannot be reassigned // Error message!

Let’s create a new variable to store the name of the user:

var userName = "Nav"

if you want to reassign the value of userName you can easily do this because var is mutable

userName = "Van"

and now the value of userName is "Van".

For more information visit this: https://medium.com/techmacademy/kotlin-101-val-vs-var-behind-the-scenes-65d96c6608bf

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

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

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.

Var means Variable-If you stored any object using 'var' it could change in time.

For example:

fun main(args: Array<String>) {
    var a=12
    var b=13
    var c=12
    a=c+b **//new object 25**
    print(a)
}

Val means value-It's like a 'constant' in java .if you stored any object using 'val' it could not change in time.

For Example:

fun main(args: Array<String>) {
    val a=12
    var b=13
    var c=12
    a=c+b **//You can't assign like that.it's an error.**
    print(a)
}

In short, val variable is final (not mutable) or constant value that won't be changed in future and var variable (mutable) can be changed in future.

class DeliveryOrderEvent(val d : Delivery)
// Only getter

See the above code. It is a model class, will be used for data passing. I have set val before the variable because this variable was used to get the data.

class DeliveryOrderEvent(var d : Delivery)

// setter and getter is fine here. No error

Also, if you need to set data later you need to use var keyword before a variable, if you only need to get the value once then use val keyword

Normal

  • Val is using for static field like in Java as Static Keyword

  • Like Static in Java/ Same as in kotlin

  • And Var denotes Variable Field in Kotlin that, you can change it.

  • Mostly Static is used when you want to save value in static memory at once,

Example:

 if you assign

 val a=1
 a=3  You can not change it 
  • You can not change, this is final value and Static

    var b=2

    b=4 U can change it

val : must add or initialized value but can't change. var: it's variable can ba change in any line in code.

In kotlin we can declare variable in two types: val and var. val cannot be reassigned, it works as a final variable.

val x = 2
x=3 // cannot be reassigned

On the other side, var can be reassigned it is mutable

var x = 2
x=3 // can be reassigned

Var is a mutable variable. It is a variable that can be changed to another value. It's similar to declaring a variable in Java.

Val is a read-only thing. It's similar to final in java. A val must be initialized when it is created. This is because it cannot be changed after it is created.

var test1Var = "Hello"
println(test1Var)
test1Var = "GoodBye"
println(test1Var)
val test2Val = "FinalTestForVal";
println(test2Val);

VAR is used for creating those variable whose value will change over the course of time in your application. It is same as VAR of swift, whereas VAL is used for creating those variable whose value will not change over the course of time in your application.It is same as LET of swift.

val - Immutable(once initialized can't be reassigned)

var - Mutable(can able to change value)

Example

in Kotlin - val n = 20 & var n = 20

In Java - final int n = 20; & int n = 20;

var is a mutable variable and can be assigned multiple times and val is immutable variable and can be intialized only single time.

In Kotlin we use var to declare a variable. It is mutable. We can change, reassign variables. Example,

fun main(args : Array<String>){
    var x = 10
    println(x)

    x = 100 // vars can reassign.
    println(x)
}

We use val to declare constants. They are immutable. Unable to change, reassign vals. val is something similar to final variables in java. Example,

fun main(args : Array<String>){
    val y = 10
    println(y)

    y = 100 // vals can't reassign (COMPILE ERROR!).
    println(y)
}

I get the exact answer from de-compiling Kotlin to Java.

If you do this in Kotlin:

data class UsingVarAndNoInit(var name: String)
data class UsingValAndNoInit(val name: String)

You will get UsingVarAndNoInit:

package classesiiiandiiiobjects.dataiiiclasses.p04variiiandiiival;

import kotlin.jvm.internal.Intrinsics;
import org.jetbrains.annotations.NotNull;

public final class UsingVarAndNoInit {
  @NotNull private String name;

  @NotNull
  public final String getName() {
    return this.name;
  }

  public final void setName(@NotNull String string) {
    Intrinsics.checkParameterIsNotNull((Object) string, (String) "<set-?>");
    this.name = string;
  }

  public UsingVarAndNoInit(@NotNull String name) {
    Intrinsics.checkParameterIsNotNull((Object) name, (String) "name");
    this.name = name;
  }

  @NotNull
  public final String component1() {
    return this.name;
  }

  @NotNull
  public final UsingVarAndNoInit copy(@NotNull String name) {
    Intrinsics.checkParameterIsNotNull((Object) name, (String) "name");
    return new UsingVarAndNoInit(name);
  }

  @NotNull
  public static /* bridge */ /* synthetic */ UsingVarAndNoInit copy$default(
      UsingVarAndNoInit usingVarAndNoInit, String string, int n, Object object) {
    if ((n & 1) != 0) {
      string = usingVarAndNoInit.name;
    }
    return usingVarAndNoInit.copy(string);
  }

  public String toString() {
    return "UsingVarAndNoInit(name=" + this.name + ")";
  }

  public int hashCode() {
    String string = this.name;
    return string != null ? string.hashCode() : 0;
  }

  public boolean equals(Object object) {
    block3:
    {
      block2:
      {
        if (this == object) break block2;
        if (!(object instanceof UsingVarAndNoInit)) break block3;
        UsingVarAndNoInit usingVarAndNoInit = (UsingVarAndNoInit) object;
        if (!Intrinsics.areEqual((Object) this.name, (Object) usingVarAndNoInit.name)) break block3;
      }
      return true;
    }
    return false;
  }
}

You will also get UsingValAndNoInit:

package classesiiiandiiiobjects.dataiiiclasses.p04variiiandiiival;

import kotlin.jvm.internal.Intrinsics;
import org.jetbrains.annotations.NotNull;

public final class UsingValAndNoInit {
  @NotNull private final String name;

  @NotNull
  public final String getName() {
    return this.name;
  }

  public UsingValAndNoInit(@NotNull String name) {
    Intrinsics.checkParameterIsNotNull((Object) name, (String) "name");
    this.name = name;
  }

  @NotNull
  public final String component1() {
    return this.name;
  }

  @NotNull
  public final UsingValAndNoInit copy(@NotNull String name) {
    Intrinsics.checkParameterIsNotNull((Object) name, (String) "name");
    return new UsingValAndNoInit(name);
  }

  @NotNull
  public static /* bridge */ /* synthetic */ UsingValAndNoInit copy$default(
      UsingValAndNoInit usingValAndNoInit, String string, int n, Object object) {
    if ((n & 1) != 0) {
      string = usingValAndNoInit.name;
    }
    return usingValAndNoInit.copy(string);
  }

  public String toString() {
    return "UsingValAndNoInit(name=" + this.name + ")";
  }

  public int hashCode() {
    String string = this.name;
    return string != null ? string.hashCode() : 0;
  }

  public boolean equals(Object object) {
    block3:
    {
      block2:
      {
        if (this == object) break block2;
        if (!(object instanceof UsingValAndNoInit)) break block3;
        UsingValAndNoInit usingValAndNoInit = (UsingValAndNoInit) object;
        if (!Intrinsics.areEqual((Object) this.name, (Object) usingValAndNoInit.name)) break block3;
      }
      return true;
    }
    return false;
  }
}

There are more examples here: https://github.com/tomasbjerre/yet-another-kotlin-vs-java-comparison

Lets try this way.

Val is a Immutable constant 
    val change="Unchange" println(change)
    //It will throw error because val is constant variable
    // change="Change" 
    // println(change)
Var is a Mutable constant
    var name: String="Dummy"
    println(name)
    name="Funny"
    println(name)

I'm late to the party, but there's one difference that I haven't seen mentioned. You can use val to assign a local variable in a when expression, but trying to use var will produce a compiler error:

sealed class Token {
    data class StringToken(val value: String) : Token()
    data class BoolToken(val value: Boolean) : Token()
}

fun getToken() : Token = Token.BoolToken(true)

val output = when (val token = getToken()) {
    is Token.StringToken -> token.value
    is Token.BoolToken -> token.value.toString()
}

This allows you to get access to the correctly type-inferred value in the expressions on the right.

We use var to declare variables and we use val to create constants which in java are preceded by the reserved word final

Val is immutable and its properties are set at run time, but you can use a const modifier to make it as a compile time constant. Val in kotlin is same as final in java.

Var is mutable and its type is identified at compile time.

In Kotlin, we have two types of variables: var or val. The first one, var, is a mutable reference (read-write) that can be updated after initialization. The var keyword is used to define a variable in Kotlin. It is equivalent to a normal (nonfinal) Java variable. If our variable needs to change at some time, we should declare it using the var keyword. Let's look at an example of a variable declaration:

 fun main(args: Array<String>) {
     var fruit:String = "orange"  // 1
     fruit = "banana"             // 2
 }
Related