Learn/Scala/2. Values and variables
Lesson 2 of 8
Sign in

Scala, lesson 2

Values and variables

Programs need to remember things: a player's name, a price, a score. In Scala you give a value a name with val or var.

Prefer val. Most values in a program never need to change, and when the compiler knows a name always means the same thing, your code is easier to reason about. Reach for var only when something really must change over time, like a running total.

Types

Every value in Scala has a type, and the compiler checks types before the program runs. You usually don't have to write them, because Scala infers the type from the value. You can still write it after a colon when you want to be explicit:

The ones you will use most:

TypeHoldsExample
Int

2 exercises to try what you just read.

Exercise 1

Character card

Press Ctrl Enter or Check to test your code.

Exercise 2

Piggy bank

Press Ctrl Enter or Check to test your code.

whole numbers up to about two billion
42
Longbigger whole numbers42L
Doublenumbers with a decimal point3.14
Booleantrue or falsetrue
Stringtext"hi"

Once a name has a type, it keeps it. A var declared as an Int cannot later hold a String; the compiler stops you.

Naming

Names start with a letter and use camelCase: playerName, maxHealth. They are case sensitive, so score and Score are different names. Pick names that say what the value means, not what type it is.

For a constant that never changes and is used across your program, Scala style uses an upper camel case name, like val MaxPlayers = 4.

String interpolation

Putting values inside text is so common that Scala has a shortcut. Write s right before the opening quote, then use $name for a variable or ${...} for any expression:

The f interpolator also lets you format numbers, for example with two decimals:

You can also join strings with +: "Hello, " + name. Interpolation is usually easier to read.

Further reading

  • Scala 3 Book: Variables and Data Types
  • Scala 3 Book: String Interpolation

The starter declares four values for a game character. Print them on one line in exactly this format, using string interpolation:

The program reads no input.

Use a var called savings that starts at 20. Then change it three times and print it after each step:

  1. Add a deposit of 15.
  2. Double it.
  3. Spend 8 on a snack.

Expected output:

val name = "Rowan"     // a val can never be reassigned
var score = 0          // a var can
score = score + 10     // fine
// name = "Ash"        // compile error: reassignment to val
val level: Int = 7
val price: Double = 3.5
val big: Long = 9_000_000_000L   // the L suffix makes a Long; underscores are just for reading
val ready: Boolean = true
val grade: Char = 'A'            // single quotes: one character
val city: String = "Lisbon"      // double quotes: text
val item = "tea"
val cups = 3
println(s"$cups cups of $item")            // 3 cups of tea
println(s"Twice that is ${cups * 2}")      // Twice that is 6
val total = 7.5
println(f"Total: $total%.2f")   // Total: 7.50
Rowan | level 7 | 42.5 HP | mage: true
Start: 20
After deposit: 35
Doubled: 70
After snack: 62