What is the difference between var and val in Kotlin?

Var

var name = "bobby"
var name String = "bobby"

“var” is declared an immutable variable. A variable is a variable that can be changed or that can be reassigned in the course of the program.

In above the illustration, both lines of law are principally the same, except that the data type is indicated in the alternate line.

Indicating the data type is voluntary in Kotlin, as Kotlin can infer the data type of the variable according to the value assigned to it. In “var”, values are assigned during run time.

Val

Val is used to declaring immutable variables. Once a value is assigned to a variable with the “val” keyword, it can not be altered or reassigned throughout the program. Val is analogous to the final keyword in Java.

val age = 40

Throughout the program, it’s anticipated that the value of age will remain at 35. still, an error will be thrown, If you try to assign another value to age. “val” is also a run-time constant, meaning its value has to be assigned during run time.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories