Home Android Tutorial How to Declare and Use Variables in Kotlin

How to Declare and Use Variables in Kotlin


There are two types of variables in Kotlin: read-only and mutable. Read-only variables (or constants) are declared with val and mutable with var. Every variable must be declared. Any attempt to use a variable that hasn’t been declared yet is a syntax error; thus, you are protected from accidentally assigning to a misspelled variable. The declaration also decides what kind of data you are allowed to store in the variable.

Local variables are typically declared and initialized at the same time, in which case the type of the variable is inferred to be the type of the expression you initialize it with. Int is a type that represents an integer, one of the many numerical types that can be represented in Kotlin. Similar to other languages, you can also use Byte, Short, Long, Float, and Double depending on your numerical data.

A variable refers to a memory location that stores some data. It has a name and an associated type. The type of a variable defines the range of values that the variable can hold, and the operations that can be done on those values. Although Kotlin is a statically typed language, It doesn’t require you to explicitly specify the type of every variable you declare. It can infer the type of a variable from the initializer expression.

An interesting thing from Kotlin is that most of the time you won’t need to specify the type of the objects you are working with, as long as the compiler can infer it. So we just need to write var or val depending on the type of variable we want to generate, and the type can normally be inferred. We can always specify a type explicitly.