Variables… Whether They Vary or Not
A computer program usually needs something more than simple literals. We need to perform calculations, and sometimes we need to hold those results somewhere. Classically, in programming, we call such things “variables”. In Kotlin, that winds up being a bit of a curious name, as “variable” suggests a value that can vary… which is not true in all Kotlin cases.
Declaring Variables
We have to hold our data somewhere, and in some cases that “somewhere” is a variable. Different languages have different ways of declaring variables:
- Do you need a keyword, like
var
, or not? - Do you need a data type, like
int
, or not? - Do you need to provide an initializer to establish the variable’s value, or not?
In Kotlin, the required items are a keyword (var
or val
), the name, and (in most cases) an initializer. The type may or may not be required, depending on the initializer.
Typeless Declarations
If you are initializing the variable as part of declaring it, Kotlin will infer the type of the variable.
For example:
fun main() {
var count = 5
println(count::class)
}
This gives us the same output as what we would get if we printed 5::class
:
-
class Int
in the Klassbook or other Kotlin/JS environments -
class kotlin.Int
in Android or other Kotlin/JVM environments
Here, Kotlin sees that our variable initialization code evaluates to an Int
, and so it declares the variable count
as being of type Int
.
This is one of many ways that Kotlin tries to keep the “ceremony” down and keep the language concise.
Typed Declarations
It is also possible to declare a variable with a type:
var count: Long = 5
println(count::class)
This says that the variable count
is a Long
. Even though 5
is an Int
(5L
would be the Long
equivalent), Kotlin is kind to you and will convert the literal value to a Long
as part of assigning it to the variable.
In many cases, the type is unnecessary, as Kotlin can default the variable’s type to be whatever the type is of our initial value. But there will be times when you want a variable to have a different type than the initial value, and we will see a few examples of that as we proceed through the book.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.