What is a variable?
Declaring variables
Before you start using a variable, you must declare it. To declare a variable, Kotlin provides two keywords:
val
(from value) — declares an immutable variable (just a named value or constant) that cannot be changed after it has been initialized;var
(from variable) — declares a mutable variable that can be changed (as many times as needed);
When you declare a variable, you must add its name after one of these keywords. The name of a variable cannot start with a digit. Usually, it starts with a letter. Always try to choose meaningful and readable names for variables to make your code easy to understand.
To assign a certain value to a variable, we should use the assignment operator =
.
Let's declare an immutable variable named language
and initialize it with the string "Kotlin"
.
val language = "Kotlin"
language
is not the same as Language
.Now we can access this string by the variable's name. Let's print it!
println(language) // prints "Kotlin" without quotes
val
.dayOfWeek
and print its value before and after changing it.var dayOfWeek = "Monday"
println(dayOfWeek) // Monday
dayOfWeek = "Tuesday"
println(dayOfWeek) // Tuesday
dayOfWeek
and initialized it with the value "Monday"
. Then we accessed the value by the variable name to print it. After that, we changed the variable's value to "Tuesday"
and printed this new value.=
operator.val cost = 3
val costOfCoffee = cost
println(costOfCoffee) // 3
val ten = 10
val greeting = "Hello"
val firstLetter = 'A'
println(ten) // 10
println(greeting) // Hello
println(firstLetter) // A
var
). You can only reassign values of the same type as the initial value. So, the following code is not correct:var number = 10
number = 11 // ok
number = "twelve" // an error here!
Battle of keywords: val vs var
val
. Before using var
you should be sure that val
is not suitable in that case. If it isn't, then use var
. But keep in mind, the more mutable variables in your program, the harder it will be to understand it. By the same token, immutable variables make your program easier and help to maintain a readable code. So, use val
whenever possible! You can easily replace it with var
when it becomes necessary.