Variables · 5 of 42

Final Variables

Final variables are declared using the val keyword (a final variable is a variable that can’t be reassigned).

The code on the left looks almost exactly like in the previous step, with one small change. The var was changed to val.

Try to run the code on the left, the compiler should complain on line 3, since we are trying to reassign x which is a val.

Exercise: edit the code on the left so it will run (either change the val back to var, remove the reassignment to x, or assign the result of the expression in line 3 to a different val or var).
Note: Prefer using val over var (and immutable objects over mutable ones). There are many benefits that are out of the scope of this small tour.
val x = 1 + 2 //val instead of var
println(x)
x = 3 * 4 //error: reassignment to val
println(x)

Contents

Scala basics

  1. Overview
  2. Scalculator
  3. Operators are methods
  4. Variables
  5. Final variables
  6. Printing values
  7. String interpolation
  8. String formatting
  9. Useful operations
  10. Method definition
  11. Method definition 2
  12. Method definition 3
  13. Anonymous functions
  14. Anonymous functions 2
  15. Return multiple values
  16. Declare multiple variables
  17. Assign multiple variables
  18. Loops using while
  19. Loops using for
  20. Loops without loops
  21. If
  22. Match as a switch
  23. Arrays
  24. Lists
  25. Sets
  26. Maps
  27. Mutable collections
  28. Collections: accessing elements
  29. Collections: concatenation
  30. Mutable collection operations
  31. Immutable collections with var
  32. Collections: useful methods
  33. Classes
  34. Classes, continued

What's new in Scala 3

  1. Scala 3: what changed
  2. Optional braces & new control syntax
  3. Top-level definitions & @main
  4. Enums & ADTs
  5. Extension methods
  6. given & using
  7. Union & intersection types
  8. Smaller niceties