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.

Syntax

val variable_name = value
OR
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.

Example

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.

Syntax

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

Example

var numberofballs = 6
numberofballs = 8

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