Start learning free

LESSON 4 OF 348 · WELCOME TO KOTLIN

Variables in Kotlin: val, var and Types

Lesson Read the full explanation

In computer science, data is anything that is meaningful to the computer. Java provides a large number of data types, the most frequently used being:

  • int - represents integer numbers like 3 and -12
  • double - represents floating point numbers like 3.14
  • char - represents a single character like 'a', 'Z' or '?'
  • String - represents a sequence of characters like "John Doe"
  • boolean - represents one of two values: true or false

For example, computers distinguish between numbers, such as the number 12, and strings, such as "12", "dog", or "123 cats", which are collections of characters. Computers can perform mathematical operations on a number, but not on a string.

Variables are containers for storing values. A piece of information / data lives in memory and we use a variable to store and descriptively label that data.


Variable declaration:

To create / declare a variable, we must tell Kotlin the variable's data type followed by the variable's name, like so:

val name: String = "AlgoCademy"

creates a String variable named name.


Variable initialization:

We can initialize a variable to an initial value in the same line as it is created using the assignment operator (=). This code:

val name = "AlgoCademy"

creates a new String variable named name and assigns it an initial value of "AlgoCademy".

When executing this code, Kotlin will allocate some memory, then it will store the string "AlgoCademy" in that memory and finally will attach this name label to that memory location.

You can think of this memory location as a box. In that box, we put string "AlgoCademy". Then, we put the label name on this box.


val vs var:

Kotlin has two ways to declare a variable. val creates a read-only (immutable) variable — once set, it cannot be reassigned. var creates a variable you can reassign later. Prefer val whenever the value will not change.

val name = "AlgoCademy" // read-only
var age = 10            // reassignable
age = 11                // OK
// name = "Other"       // error: val cannot be reassigned

Accessing values in variables:

Now we can use this label anywhere in our program to access the value in that box. We can print it for example:

// We create and initialize two variables:
val name: String = "AlgoCademy"
val age: Int = 10

// We access the variables:
println(name)
println(age)

The output of this code is:

AlgoCademy
10

Important notice:

We almost never want to create a variable without initializing it! It's a bad coding practice and can create a lot of problems.


Assignment
Follow the Coding Tutorial and let's create some variables.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    KOTLIN · WELCOME TO KOTLIN

    Variables in Kotlin, explained

    What a variable is

    A variable is a named container for a value. The program keeps the value in memory, and the variable's name is the label you use to get it back. Without variables, a program would have to repeat every value each time it needed it, and it couldn't keep results for later.

    Data types

    Every value in Kotlin has a type. The ones you meet first are:

    • Int for whole numbers such as 3 and -12;
    • Double for numbers with a fractional part, such as 3.14;
    • Char for a single character, written in single quotes, such as 'a' or '?';
    • String for text, such as "John Doe";
    • Boolean for one of two values, true or false.

    Type names start with a capital letter in Kotlin. The type decides what you can do with a value: you can do arithmetic on the number 12, but not on the string "12".

    Declaring a variable with val and var

    Kotlin has two keywords for creating a variable. Both are followed by the name, an optional type after a colon, and an initial value after =:

    val name: String = "AlgoCademy"
    var age: Int = 10
    
    • val makes a read-only variable. Once it has a value, it can't be reassigned.
    • var makes a variable whose value you can reassign later.

    Use val by default, and switch to var only when the value really must change. A val tells the reader that the value stays the same, and it lets the compiler catch accidental changes:

    val name = "AlgoCademy"
    var age = 10
    age = 11
    name = "Other"
    

    The assignment age = 11 is fine. The last line doesn't compile, and the compiler reports 'val' cannot be reassigned.

    Type annotations and type inference

    The type after the colon is optional when you give an initial value. Kotlin works out the type from the value, which is called type inference. These two lines are equivalent:

    val name: String = "Michael"
    val name = "Michael"
    

    Both give name the type String. The type is then fixed. A variable declared as an Int can't later hold a string:

    var age: Int = 30
    age = "31"
    

    The second line is a compile error: assignment type mismatch: actual type is 'String', but 'Int' was expected. Likewise, val age: Int = "30" fails with initializer type mismatch: expected 'Int', actual 'String'.

    Whole-number literals are Int when they fit in 32 bits. A literal that is too big, such as 3000000000, is a Long, a 64-bit integer type.

    Using a variable

    Once a variable exists, you use its name wherever you need its value:

    val name: String = "AlgoCademy"
    val age: Int = 10
    
    println(name)
    println(age)
    
    AlgoCademy
    10
    

    Printing a variable shows its value, not its name. Inside a string, $name inserts the value: println("Welcome to $name") prints Welcome to AlgoCademy.

    Always initialize

    Create a variable with its first value. In Kotlin this is more than good style, because the compiler checks it. A local variable that is read before it has a value does not compile:

    val age: Int
    println(age)
    

    The compiler reports variable 'age' must be initialized.

    Naming and other mistakes

    • Quotes around a number. "30" is a String. For a number, write 30.
    • Repeating var when reassigning. var age = 31 in the same scope tries to declare a second variable with the same name, which the compiler rejects as conflicting declarations. To change the value, write age = 31.
    • Case matters. age and Age are different names, and a misspelled name gives an unresolved reference error.
    • Mixing up the colon and the equals sign. The type goes after a colon, and the value goes after =.

    The exercise

    The lesson has three steps, each one line long.

    1. Declare a read-only variable named name, with the type String and the value "Michael". Use val.
    2. Declare a mutable variable named age, with the type Int and the value 30. Use var, and no quotes around the number.
    3. Reassign age to 31 with a plain =. No keyword is needed, because the variable already exists. This is allowed because age is a var.

    Together they make:

    val name: String = "Michael"
    var age: Int = 30
    age = 31
    

    Key takeaways

    • A variable is a named container for a value, and every value has a type.
    • val is read-only, var can be reassigned, and val is the default choice.
    • The type goes after a colon, and Kotlin can infer it from the initial value.
    • A variable's type is fixed, so assigning a value of another type is a compile error.
    • Reassigning uses = alone, without val or var.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free