Start learning free

LESSON 4 OF 414 · WELCOME TO SCALA

Variables in Scala: val, var and Types

Lesson Read the full explanation

In computer science, data is anything that is meaningful to the computer. Scala 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 use val or var followed by the variable's name, and we can also tell Scala the variable's data type after a colon, 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, Scala 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.


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 = "AlgoCademy"
val age = 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.


val vs var:

Scala has two ways to declare a variable. val declares an immutable value — once set, it can't be reassigned. var declares a mutable variable you can reassign later. Prefer val; Scala favors immutability.

val pi = 3.14   // immutable — reassigning pi is an error
var score = 0   // mutable
score = 10      // OK: var can change

You'll see both throughout the coding tutorials — reach for val unless a value genuinely needs to change.


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

    SCALA · WELCOME TO SCALA

    Variables in Scala, explained

    Data types and variables

    Programs work with data, and Scala gives that data types. The ones you will use most are:

    • Int: whole numbers such as 3 and -12;
    • Double: numbers with a fractional part, such as 3.14;
    • Char: a single character in single quotes, such as 'a';
    • String: text in double quotes, such as "John Doe";
    • Boolean: either true or false.

    The type matters because it decides what you can do with a value. The number 12 and the string "12" look alike, but 12 + 1 is 13 and "12" + 1 is "121".

    A variable is a name attached to a value stored in memory. You can picture a box with a label: the value is inside, and the name is the label you use to find it again.

    Declaring a variable

    A declaration starts with val or var, then the name, then optionally a colon and the type, then = and the initial value:

    val name: String = "AlgoCademy"
    val age = 10
    

    The first line states the type, String, after the name. The second leaves it out, and Scala infers Int from the value. Both are correct. Writing the type is useful for documentation; leaving it out keeps simple code short.

    Once a variable exists, use its name to read its value:

    val name = "AlgoCademy"
    val age = 10
    println(name)
    println(age)
    
    AlgoCademy
    10
    

    Always give a variable a value when you declare it. In Scala a local variable cannot be declared without one.

    val versus var

    Scala has two keywords for variables:

    • val makes a value that can't be reassigned after it is set.
    • var makes a variable that can be reassigned.
    val pi = 3.14
    var score = 0
    score = 10
    

    Assigning to score is fine. Assigning to pi, as in pi = 3.2, is a compile error: Reassignment to val pi. Prefer val by default, because a value that never changes is easier to reason about, and switch to var only when the value genuinely needs to change.

    Gotchas

    • The type is fixed. A variable declared as Int can't later hold a string. After var x = 5, the assignment x = "five" fails to compile with a message that it found a String where an Int is required.
    • The type must match the value. val age: Int = "30" is an error for the same reason. Numbers are written without quotes; "30" is a string.
    • Reassign without the keyword. After var age = 30, change it with age = 31. Writing var age = 31 again would try to declare a second variable of the same name.
    • Increment with +=. Scala has no ++ operator. Write count += 1.

    The exercise

    The exercise has three steps, each on its own line:

    1. Declare a val named name of type String with the value "Michael".
    2. Declare a var named age of type Int with the value 30. It is a var because the next step changes it.
    3. Reassign age to 31. The assignment uses only =, with no keyword, and is allowed because age is a var.
    val name: String = "Michael"
    var age: Int = 30
    age = 31
    

    Key takeaways

    • A variable is a name for a stored value, and every value has a type.
    • Declare with val for values that stay fixed and var for values that change.
    • The type can be written after a colon or inferred from the value.
    • Reassigning a val, or giving a variable a value of the wrong type, is a compile error.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free