Skip to content
LumenaryAcademy
Foundations 50 min

Values, types and expressions

val and var, the basic types, type inference, and a language in which almost everything has a value.

Code tested · 5AI-draftedAwaiting review by a computer scientist
MotivationH

Values that do not change

Think about a spreadsheet. You type =A1*B1 into a cell, and from then on that cell is the product of two others. You never write a step that says "now change C1"; the value is defined once and the sheet keeps it consistent. Spreadsheets are the most widely used programming tool on earth, and part of the reason is that this style is easy to reason about: to know what a cell holds, you read its definition, not the history of everything that ever touched it.

Scala encourages the same habit. Most names in a Scala program are introduced with val and never change. Most constructs, including if, match and whole blocks of code, are expressions that compute a value rather than statements that change something. When you need a value that depends on a condition, you write the condition inside the definition instead of declaring a variable and assigning it in two branches.

This lesson covers the material every Scala program is built from: named values, the basic types and how the compiler infers them, the type hierarchy that ties them together, expressions that produce values, and loops. Some of it will look familiar from other languages. The parts that differ, such as if returning a value or == comparing strings by content, are exactly the parts worth slowing down for.

DefinitionsH

val, var and type inference

Definition— val and var

val name = expression binds a name to a value permanently: assigning to it again is a compile error. var name = expression creates a variable that can be reassigned with name = newValue. Both must be given a value when they are declared.

Definition— Type inference

The compiler works out the type of a val or var from the expression on the right, so val copies = 3 gives copies the type Int. You may write the type yourself after a colon, val copies: Int = 3, and the compiler then checks that the value fits.

Here is a program that uses the common types:

scala
@main def values(): Unit =
  val title = "The River Between"
  val copies = 3
  val price = 12.5
  val onLoan = false
  val shelf = 'K'
  var borrowed = 0
  borrowed += 1
  borrowed += 1
  println(s"$title: $copies copies at $price each, on loan: $onLoan")
  println(s"Shelf $shelf, borrowed $borrowed times")

  val distanceToSun = 149_600_000_000L
  println(distanceToSun * 2)
  println(7 / 2)
  println(7 % 2)
  println(7 / 2.0)
  println(0.1 + 0.2)
  println(Int.MaxValue + 1)
  println(BigInt(2).pow(100))
text
The River Between: 3 copies at 12.5 each, on loan: false
Shelf K, borrowed 2 times
299200000000
3
1
3.5
0.30000000000000004
-2147483648
1267650600228229401496703205376

The inferred types are String, Int, Double, Boolean and Char. The table summarises the basic types:

TypeWhat it holdsLiterals
Int32-bit signed integer, about ±2.1 billion42, -7, 1_000_000
Long64-bit signed integer42L, 149_600_000_000L
Double64-bit floating point3.14, 2.0, 6.02e23
Float32-bit floating point (rarely used)3.14f
Booleantrue or falsetrue, false
Charone UTF-16 code unit'K', 'é'
Stringtext (a Java string)"hello", """multi-line"""
BigInt, BigDecimalintegers and decimals of any sizeBigInt(2), BigDecimal("0.10")
Unit"no interesting value"; its only value is ()()

The output above has three traps that bite every newcomer once:

  • Integer division truncates. 7 / 2 is 3, and 7 % 2 is the remainder 1. If either side is a Double, the division is in floating point: 7 / 2.0 is 3.5.
  • Floating point is binary. 0.1 + 0.2 prints 0.30000000000000004 because neither 0.1 nor 0.2 has an exact binary representation. For money, use BigDecimal or count in whole cents with a Long.
  • Int arithmetic wraps around silently. Int.MaxValue + 1 is the most negative Int. Use Long when values may exceed about two billion, and BigInt when they may exceed anything. The literal 149_600_000_000L needs its L: without it the number does not fit in an Int and the compiler rejects it. Underscores in numbers are only for readability.

Why val is the default

Experienced Scala programmers write val almost everywhere and reach for var only inside a small, local loop. The reasons are practical. A val can be read anywhere without asking "has someone changed this since?". It is safe to share between threads (lesson 8). And code made of vals can be rearranged, extracted into functions or tested in isolation without changing its meaning. When you catch yourself declaring a var and assigning it in several branches, there is usually an expression that computes the value directly, and this lesson shows the main ones.

IntuitionH

Everything is an object, and every object has a type

In Scala, numbers are objects with methods, and operators are just methods with symbolic names. 1 + 2 is shorthand for 1.+(2): calling the method + on the object 1. Any method with one argument can be written in this infix style, so 3.max(9) can also be written 3 max 9, and 1.to(4) as 1 to 4, which is how you will usually see ranges.

scala
@main def objects(): Unit =
  println(1 + 2 == 1.+(2))
  println((-7).abs)
  println(3.max(9))
  println(1.to(4))
  println(65.toChar)
  println('A'.toInt)
  println("42".toInt + 1)
  println("4x2".toIntOption)
  println("42".toIntOption)
  println(3.99.toInt)
  println(10.toDouble / 4)
text
true
7
9
Range 1 to 4
A
65
43
None
Some(42)
3
2.5

Conversions are methods too: toInt, toDouble, toChar, toString. Converting a Double to an Int truncates toward zero, so 3.99.toInt is 3. Converting a String with toInt throws an exception if the text is not a number; toIntOption instead returns Some(42) or None, a safer pattern you will study properly in lesson 7.

Note

Write (-7).abs, with parentheses. Scala 3 reads -7.abs as the literal -7 followed by .abs (which gives 7), but some readers expect -(7.abs), so the compiler warns: Ambiguous literal. Parentheses make your intent plain.

The type hierarchy

Every type in Scala fits into one tree.

  • Any is at the top: every value is an Any.
  • AnyVal is the parent of the value types: Int, Long, Double, Float, Boolean, Char, Byte, Short and Unit. The compiler stores these as plain machine values where it can, so they cost no more than Java's primitives.
  • AnyRef is the parent of every other type: String, collections, your own classes. On the JVM it is the same as Java's Object.
  • Nothing is at the bottom: it is a subtype of every type and has no values at all. An expression of type Nothing never finishes normally; throw has this type, which is why val n: Int = throw Exception("no") type-checks.
  • Null is the type of null, which exists for Java interoperability. Idiomatic Scala avoids null entirely and uses Option instead.

When two branches of an expression produce different types, the compiler looks for a type that covers both. In Scala 3 that can be a union type: if ok then "a" else 0 has type String | Int, "either a String or an Int". You rarely want such a value, and the compiler's error messages will show you when you have made one by accident.

Worked examplesH

Expressions everywhere

In many languages, if is a statement: it does something. In Scala, if, match and blocks are expressions: they produce something.

scala
def grade(score: Int): String =
  if score >= 90 then "excellent"
  else if score >= 75 then "good"
  else if score >= 50 then "pass"
  else "not yet"

def dayKind(day: String): String = day match
  case "Saturday" | "Sunday" => "weekend"
  case _                     => "weekday"

@main def expressions(): Unit =
  val area =
    val width = 4.0
    val height = 2.5
    width * height
  println(area)
  for s <- List(95, 80, 51, 12) do
    println(s"$s -> ${grade(s)}")
  println(dayKind("Sunday"))
  println(dayKind("Tuesday"))
  val result: Unit = println("printing is a side effect")
  println(result)
text
10.0
95 -> excellent
80 -> good
51 -> pass
12 -> not yet
weekend
weekday
printing is a side effect
()
  • grade is a chain of if ... then ... else whose value is the method's result. There is no return: a method returns the value of its body.
  • dayKind uses match, Scala's pattern-matching expression. Each case is tried in order; | combines alternatives and _ matches anything. Lesson 4 shows how much more match can do.
  • The indented block after val area = defines two local values and then computes width * height. A block's value is the value of its last expression, and the helper names width and height are invisible outside it. This is a tidy way to compute a value in several steps without leaving temporary names lying around.
  • println returns Unit, whose only value prints as (). A function that returns Unit is called for its side effect, such as printing or writing a file, not for its result.

An if without an else also has a value, but it is Unit, so it is only useful for side effects: if debug then println("checking").

Loops and ranges

Scala has a for loop that walks over anything iterable, and a while loop for when you really do need a condition-controlled loop.

scala
@main def loops(): Unit =
  for i <- 1 to 3 do print(s"$i ")
  println()
  for i <- 0 until 10 by 3 do print(s"$i ")
  println()
  for i <- 5 to 1 by -2 do print(s"$i ")
  println()

  for
    row <- 1 to 3
    col <- 1 to 3
    if row < col
  do print(s"($row,$col) ")
  println()

  val squares = for n <- 1 to 5 yield n * n
  println(squares)

  var n = 27
  var steps = 0
  while n != 1 do
    n = if n % 2 == 0 then n / 2 else 3 * n + 1
    steps += 1
  println(s"27 reaches 1 after $steps steps")
text
1 2 3 
0 3 6 9 
5 3 1 
(1,2) (1,3) (2,3) 
Vector(1, 4, 9, 16, 25)
27 reaches 1 after 111 steps
  • 1 to 3 includes both ends; 0 until 10 excludes the upper end. by sets the step, which may be negative.
  • A for can have several generators (row <- ..., col <- ...), which nest like loops inside loops, and guards (if row < col) that skip some combinations.
  • With yield, for becomes an expression that builds a new collection from the values it yields. Here it builds a Vector of squares. This form, the for comprehension, is much more general than a loop: lesson 5 uses it on lists, and lesson 7 uses it to chain operations that might fail.
  • The while loop counts the steps of the Collatz process for 27. It needs vars because it is all about changing state. This is the legitimate home of var: a small, local loop whose mutation nobody outside can see.

Strings

A Scala String is a Java string, with many extra methods added by the standard library:

scala
@main def strings(): Unit =
  val name = "Mariana Souza"
  println(name.length)
  println(name.toUpperCase)
  println(name.split(" ").toList)
  println(name.contains("Souza"))
  println(name.replace("a", "4"))
  println(name.reverse)
  println(name(0))
  println(name.take(7))
  println(name.count(_ == 'a'))

  val a = "scala"
  val b = "SCALA".toLowerCase
  println(a == b)
  println(a eq b)
text
13
MARIANA SOUZA
List(Mariana, Souza)
true
M4ri4n4 Souz4
azuoS anairaM
M
Mariana
4
true
false

name(0) gets the character at index 0 (indexes start at zero, and Scala uses parentheses, not square brackets, for indexing). take(7) keeps the first seven characters. count(_ == 'a') counts characters for which the test is true; _ == 'a' is a short way to write a small function, explained in the next lesson.

The last two lines matter. In Scala, == compares values: two strings with the same characters are equal, whoever built them. That is different from Java, where == on strings compares references and is a classic bug. If you ever need to know whether two names refer to the very same object in memory, Scala's operator for that is eq, and here it says false because toLowerCase built a new string. You will almost never need eq.

Common misconceptionsH

Common misconceptions

Misconception

"A val holding a collection can never change, so its contents are frozen." A val means the name always refers to the same object. If that object is itself mutable, such as an Array or a scala.collection.mutable.Buffer, its contents can still change. Scala's default collections (List, Vector, Map, Set) are immutable, so with them a val really does mean a fixed value; that combination is what Scala programmers rely on.

Misconception

"Leaving out the type makes Scala dynamically typed." Every value still has a static type, fixed at compile time; the compiler simply writes it for you. Hover over a name in your editor and Metals or IntelliJ will show it. Teams usually write types explicitly on public methods (as documentation and to keep error messages local) and let the compiler infer the types of local values.

Misconception

"if without else returns nothing, so assigning it is an error." It compiles, and the value is Unit, which is almost never what you meant. If you find yourself assigning an if without an else, add the else branch.

Misconception

"for is just a loop." Without yield, it is a loop run for its side effects. With yield, it is an expression that builds a new collection, or more generally chains computations; the compiler translates it into calls to map, flatMap and withFilter, as lesson 5 shows.

Exercises

Exercises

Predict each answer before running the code, then check yourself in Scastie or with scala run.

1. Values, types and expressions

Warm-upComputational

What does this program print?

@main def ex(): Unit =
  val a = 17 / 5
  val b = 17 % 5
  val c = 17 / 5.0
  println(s"$a $b $c")

2. Values, types and expressions

Warm-upHuman

What happens when you compile this?

@main def ex(): Unit =
  val x = 5
  x = 6
Choose one

3. Values, types and expressions

CoreComputational

What does this program print?

@main def ex(): Unit =
  val total =
    val base = 10
    val bonus = if base > 5 then 3 else 0
    base * 2 + bonus
  println(total)

4. Values, types and expressions

CoreComputational

What does this line print? (Ignore the trailing space.)

for i <- 10 to 1 by -3 do print(s"$i ")

5. Values, types and expressions

CoreComputational

What is the value of count after this loop?

var count = 0
for
  i <- 0 until 12 by 4
  j <- 1 to 2
do count += 1

6. Values, types and expressions

CoreHuman

val s = "Sca". What does println(s + "la" == "Scala") print, and why?

Choose one

7. Values, types and expressions

StretchHuman

In Scala 3, what type does the compiler infer for v in val v = if ok then "yes" else 0?

Choose one

Further reading and resources