Skip to content
AgileLogics
4 min read

Values and Variables

Prerequisites: Your first program

Scala has two ways to name a value:

@main def values(): Unit =
  val city = "Lagos"
  var temperature = 24
  println(s"It is $temperature degrees in $city")

  temperature = 27
  temperature += 1
  println(temperature)
It is 24 degrees in Lagos
28
  • val — a value: it can't be reassigned after it's set.
  • var — a variable: it can be reassigned.
  • s"..." is a string with $name placeholders — the Strings lesson covers it.

Prefer val

@main def reassign(): Unit =
  val city = "Lagos"
  city = "Accra"
-- [E052] Type Error: Main.scala:3:7 -------------------------------------------
3 |  city = "Accra"
  |  ^^^^^^^^^^^^^^
  |  Reassignment to val city
  |
  | longer explanation available when compiling with `-explain`
1 error found

Idiomatic Scala uses val almost everywhere. Code where values never change is easier to read (a name always means the same thing), and safer with concurrency. Use var only when you have a good reason, such as a counter in a small loop.

Naming

  • Names use camelCase: firstName, totalPrice.
  • Constants are often PascalCase in objects: MaxUsers.
  • Names are case-sensitive: city and City are different.

Practice

Store a product name and price with val, a quantity with var, add 2 to the quantity, and print Coffee: 3 x 3.5.

Show solution
@main def shop(): Unit =
  val product = "Coffee"
  val price = 3.5
  var quantity = 1
  quantity += 2
  println(s"$product: $quantity x $price")
Coffee: 3 x 3.5