Kotlin Variables

A variable refers to a memory location that stores some data.
You can declare variables in Kotlin using the val and var keywords.

A variable declared with the val keyword is read-only (immutable). It cannot be reassigned after it is initialized.

val name = "Kotlin"
name = "Language" //Error: val can not be reassigned

It is similar to the final variable in Java.

Variable declared using var keyword is mutable. It can be reassigned after it is initialized.

val name = "Kotlin"
name = "Language" //No error. It works

It is similar to regular variable in Java.

Type inference:
In Kotlin, it is not mandatory to explicitly specify the type of variable that you declare. The Kotlin compiler will automatically infer the type of the variable from the initialized section.

val name = "Kotlin" // type infered as "String"
val value = 100 //type infered as "Int"

You can also explicitly define the type of the variable.

val name: String = "Kotlin"
val value: Int = 100

Type of the variable declaration mandatory if you dont initialize the variable.

val name // Error: variable must either have a Type annotation or be initialized
name = "Kotlin"

You can also declare something like this.

val name: String //works
name = "Kotlin"

Mansi Vaghela LinkedIn Twitter Github Youtube