Start learning free

LESSON 13 OF 414 · VARIABLES

Constants in Scala: Declaring Values with val

Lesson Read the full explanation

There is a special type of variable in Scala, which is called constant or val.

A constant is a variable that we do not want to change the value of during the whole program.


Creation:

You create a constant variable just like you create a normal one, but using the keyword val instead of var:

val ourName = "AlgoCademy"

println(ourName) // Output: AlgoCademy

Reassignment not allowed:

However, a val variable cannot be reassigned because it is constant. If you try to reassign a val variable, you'll get an error.

For example, this code:

val ourName = "AlgoCademy"

ourName = "Andy" // Here is the problem

would produce the compile error Reassignment to val ourName


Usage:

It seems like constants are just variables with some limitations. So, why use them when we can do the same things (and more) with normal variables?

The power of constants lies in their limitation! Constants were invented to provide some level of guarantee that the code can't change the underlying value.

This is not of much importance for a smaller project, but matters on a larger project with multiple components written by multiple authors.

Picture this: You are the first developer to have ever worked at a new startup. When you have written the core code, you created some important variables that describe your company:

val companyName = "Apple"
val foundingDate = "April 1st, 1976"
val founderName = "Steve Jobs"

Ten years later, your company blew up and you have hundreds of Software Engineers managing millions of lines of code.

I bet you wouldn't love it if a Junior Developer was able to do this successfully:

companyName = "Microsoft"
founderName = "Bill Gates"

But you are smart! You made those variables constants ten years ago and have nothing to worry about now. As for the Junior, they'll just get an error and probably a slap on the wrist by their manager.


Assignment
Follow the Coding Tutorial and let's work with constants!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    SCALA · VARIABLES

    Constants in Scala, explained

    What a constant is

    A constant is a name whose value is set once and never changes. In Scala you create one with val instead of var:

    val ourName = "AlgoCademy"
    
    println(ourName)
    
    AlgoCademy
    

    Reading the value works as with any variable. The difference appears when something tries to change it:

    val ourName = "AlgoCademy"
    
    ourName = "Andy"
    
    -- [E052] Type Error ------------------------------------------------------
      |  ourName = "Andy"
      |  ^^^^^^^^^^^^^^^^
      |  Reassignment to val ourName
    

    This is a compile error, so the program never starts. The compiler found the problem before any code ran.

    Why limit yourself

    A var can do everything a val can and more, so why choose the restricted one? Because the restriction is a promise. When you read a val, you know its value is the same on every line that follows. You don't have to scan the rest of the program for a hidden assignment. In a big program written by many people, that promise makes code far easier to follow, and a colleague who accidentally reassigns an important value gets an immediate compiler error instead of a strange bug.

    That is why Scala programmers declare everything with val by default and switch to var only when the value really has to change, such as a counter or a running total.

    The exercise step by step

    The starting program tries to change a constant:

    val pi = 3.14
    
    pi = 5
    
    println(pi)
    
    1. Find the error. The compiler points at pi = 5 and says Reassignment to val pi.
    2. Decide what is right. The value of pi should stay 3.14, so the program is wrong to change it. The declaration is fine as it is.
    3. Delete the assignment line. Leave the declaration and the println line untouched.

    Switching to var pi = 3.14 would also compile, but it would print 5 and give up the guarantee that makes pi trustworthy.

    The solution in Scala

    val pi = 3.14
    
    
    
    println(pi)
    

    The blank lines are where the assignment used to be. They make no difference. The program prints:

    3.14
    

    Scala infers that pi is a Double from the literal 3.14, so no type annotation is needed.

    What val does and does not freeze

    val fixes which value the name refers to. It does not always make the value itself unchangeable. A mutable collection stored in a val can still be modified:

    import scala.collection.mutable.ArrayBuffer
    
    val buf = ArrayBuffer(1, 2)
    buf += 3
    println(buf)
    
    ArrayBuffer(1, 2, 3)
    

    The name buf still refers to the same buffer, but the buffer's contents changed. Only an assignment such as buf = ArrayBuffer(9) would be refused. Numbers and strings are immutable themselves, so a val holding one never changes at all.

    Common mistakes

    • Changing val to var to silence the error. This removes the protection. First ask whether the value should change at all.
    • Thinking a constant must be written in capitals. Scala does not require it. A val is a constant because of the keyword, whatever its name looks like.
    • Declaring the same name twice. Writing val pi a second time in the same block is a different error: the name is already defined.
    • Expecting a runtime failure. The reassignment is caught while compiling, so no output appears before the error.

    Key takeaways

    • val creates a name that can be assigned only once.
    • Reassigning it is a compile error: Reassignment to val.
    • Use val by default and var only for values that must change.
    • A val can't be re-pointed, but a mutable object it refers to can still be modified.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free