Variables in Kotlin

As you all know, a variable is a container that is used for storing value. In Kotlin, you can declare variables using two keywords-

val Keyword in Kotlin

val keyword is used to create a read-only variable. Variable created using val keyword is equivalent to a final variable in Java. You must initialize variable at the time of creation.


val variable_name = value
val variable_name: DataType = value

When data type of a variable is not specified, then its data type is inferred from the value assigned to it.


val numberofballs = 6
numberofballs = 8 // It will give compile-time error

As you can see above, when we try to change the value of numberofballs variable it will give compilation error.

var Keyword in Kotlin

If you want to create a variable whose value can be changed to another value simply by reassigning it, then use var keyword.


var variable_name: DataType
var variable_name: DataType = value
var variable_name = value


var numberofballs = 6
numberofballs = 8

Note- Initializing variable at the point of creation is optional. Example-
var mobile: String
mobile = "Samsung Galaxy"