Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 37 ยท Collections

Tuples, Options and Ranges

Learn Scala tuples for grouping values, Option to model missing values without null, safe handling with map, getOrElse and pattern matching, and Range, Iterator and LazyList basics.

Three small types appear in nearly every Scala program. Tuples group a few values without a class. Option represents a value that may be missing, replacing null. Ranges and iterators describe sequences of numbers or items without building a big collection. You have met all three briefly; this lesson makes them solid. Scala code is read-only, with runnable Java or Kotlin counterparts.

Tuples

A tuple holds a fixed number of values of possibly different types:

SCALA
val person = ("Ada", 36)             // (String, Int)
val point = (3.0, 4.0, "origin")     // (Double, Double, String)

person._1       // "Ada"
person._2       // 36

Scala 3 supports tuples of any size. Instead of _1 and _2 you usually destructure:

SCALA
val (name, age) = person
println(s"$name is $age")     // Ada is 36

Tuples shine as quick return values:

SCALA
def minMax(xs: List[Int]): (Int, Int) = (xs.min, xs.max)

val (lo, hi) = minMax(List(4, 9, 1, 7))   // lo = 1, hi = 9

They also appear in maps ("a" -> 1 is ("a", 1)), zip, partition and groupBy. For anything with more than a couple of fields, or fields that deserve a name, use a case class instead: (String, Int, Boolean) tells the reader nothing, while User(name, age, active) does.

Java has no tuples. A record plays the same role, and it is runnable:

Java A tuple-like return value in Java (record)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Option: a value that may be missing

null is the "billion dollar mistake": any reference might be null, and the compiler will not warn you. Scala's answer is Option[A], which has exactly two forms:

  • Some(value): there is a value.
  • None: there is not.
SCALA
def findUser(id: Int): Option[String] =
  if id == 1 then Some("ada") else None

findUser(1)    // Some(ada)
findUser(2)    // None

The type Option[String] is a loud signal to callers: "you must decide what to do when this is empty". There is no way to forget.

Using an Option

SCALA
val maybeName: Option[String] = findUser(1)

maybeName.getOrElse("guest")      // "ada"
findUser(9).getOrElse("guest")    // "guest"
maybeName.isDefined               // true
maybeName.isEmpty                 // false
maybeName.map(_.toUpperCase)      // Some(ADA)
maybeName.filter(_.length > 5)    // None
maybeName.orElse(Some("fallback")) // Some(ada)

Prefer map, getOrElse and pattern matching over .get, which throws on None.

SCALA
maybeName match
  case Some(n) => println(s"Hello $n")
  case None => println("Nobody home")

Chaining with flatMap and for

SCALA
case class Address(city: Option[String])
case class User(address: Option[Address])

def cityOf(user: Option[User]): Option[String] =
  for
    u <- user
    a <- u.address
    c <- a.city
  yield c

If any step is None, the result is None, with no nested if (x != null) checks. flatMap is what makes this work, and Option also supports foreach, exists and toList:

SCALA
Some(3).toList            // List(3)
None.toList               // List()
List(Some(1), None, Some(3)).flatten  // List(1, 3)

Converting from a risky call:

SCALA
Option(javaMethodThatMayReturnNull())   // None if null, else Some(value)
"42".toIntOption                        // Some(42)
"abc".toIntOption                       // None

Option(x) wraps a possibly-null value from Java code; Some(null) would be a trap, so avoid it.

The runnable Java comparison uses java.util.Optional, which has similar methods:

Java Optional in Java (Option comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Ranges

A Range is an immutable sequence of integers stored as three numbers (start, end, step), so even a huge range uses almost no memory.

SCALA
1 to 5              // Range 1, 2, 3, 4, 5
1 until 5           // Range 1, 2, 3, 4
10 to 1 by -3       // Range 10, 7, 4, 1
(1 to 5).toList     // List(1, 2, 3, 4, 5)
(1 to 5).sum        // 15
(1 to 5).map(_ * 2) // Vector(2, 4, 6, 8, 10)
'a' to 'e'          // NumericRange: a, b, c, d, e
0.0 to 1.0 by 0.25  // NumericRange: 0.0, 0.25, 0.5, 0.75, 1.0

Ranges support every sequence method and are the usual source for for loops and test data:

SCALA
(1 to 20).filter(n => n % 3 == 0)        // Vector(3, 6, 9, 12, 15, 18)
(1 to 5).foldLeft(1)(_ * _)              // 120, a factorial
(1 to 3).flatMap(i => (1 to i).map(j => (i, j)))

Kotlin ranges are the closest relative, and runnable:

Kotlin Ranges (Kotlin comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Iterators

An Iterator hands out elements once, one at a time, and can be used only once:

SCALA
val it = List(1, 2, 3).iterator
it.hasNext   // true
it.next()    // 1
it.next()    // 2
it.toList    // List(3): the rest

Iterators are lazy, so they suit large inputs like lines of a file:

SCALA
import scala.io.Source
val longLines = Source.fromFile("data.txt").getLines().filter(_.length > 80).take(10).toList

Iterators support map, filter and most other methods, but once you have consumed one, it is empty. Never use an iterator after passing it to another method.

LazyList reminder

A LazyList is the cached, possibly infinite sequence from the list lesson:

SCALA
val evens = LazyList.from(0, 2)           // 0, 2, 4, ...
evens.take(4).toList                       // List(0, 2, 4, 6)

Common mistakes

  • Using .get on an Option without checking. It throws NoSuchElementException.
  • Wrapping a nullable Java value in Some instead of Option.
  • Reaching for tuples with four or five fields. A case class is clearer.
  • Reusing an Iterator after it has been consumed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the pattern val (a, b) = (1, 2) do?

    Destructuring pulls the elements of the tuple into separate names.
  2. 2. Which two values can an Option[A] hold?

    Option is either Some(value) or None.
  3. 3. How do you wrap a value that might be null returned by Java code?

    Option(x) gives None when x is null and Some(x) otherwise. Some(null) would be a bug.
  4. 4. What is the result of (1 until 5).toList?

    until excludes the end, so the range is 1, 2, 3, 4.
  5. 5. Why is a Range cheap even for huge sizes?

    A Range computes elements from three numbers rather than storing them.

Summary

  • Tuples group a few values; destructure them with val (a, b) = t.
  • Option replaces null: use map, getOrElse, pattern matching and for instead of .get.
  • Option(x) wraps nullable Java values; toIntOption parses safely.
  • Ranges (to, until, by) are compact sequences that support all collection methods.
  • Iterators are one-shot and lazy; LazyList caches and can be infinite.

Next: Classes and Constructors