Skip to main content
Quick Reference

Scala Cheatsheet

Scala 3 on one page — lists, Option, case classes, pattern matching, and the traps around ==, Array, and None.

10 sections 10 tables 14 code snippets

Run a file

A file

scala analysis.scala

A list

val pages = List(412, 300, 180)

The names

NameMeaning
scalaRuns a file. The same command with no file opens the REPL. :quit leaves it
valBinds a name once. var can be assigned again
ListAn immutable linked list. map returns a new list
IntA 32-bit integer. 412L is a Long. 412.0 is a Double
s"..."Inserts a name after a dollar. A plain string leaves the dollar as text
()The only value of Unit. println returns Unit

This page is Scala 3. Akka, Spark, and Play are left out. Brace blocks still work in Scala 2.

Lists

The first value

pages.head

Index zero

pages(0)

List rules

ExpressionResult
pages.headThe first value. On Nil it throws NoSuchElementException
pages(0)Also the first value. Indexes start at 0. Past the end throws
412 :: pagesPrepends in constant time. :: associates to the right, ending at Nil
pages :+ 90Appends, and walks the whole list to do it
VectorThe immutable sequence to use when you index or update by position
==List(1, 2) == Vector(1, 2) is true. Same elements in the same order

Option

A fallback

val year: Option[Int] = None
year.getOrElse(0)

Empty rules

FormDetail
SomeHolds one value. None is the empty option
mapChanges the value inside Some. On None the result stays None
getOrElseThe value, or the fallback when the option is empty
getThrows NoSuchElementException on None
headOptionAn option, so an empty list becomes None instead of a throw
nullA Java gap. A method call on null throws. == does not

Functions

A method

def total(xs: List[Int]): Int = xs.sum

A function value

pages.map(n => n + 1)

Call rules

FormDetail
defRuns the body on every call
valStores the result of the right-hand side
lazy valStores the result on first use, then reuses it
Last expressionThe result of the function. return is rarely needed
n => n + 1A function value. _ + 1 is the short form with one argument
_ + _Two arguments, one per underscore. It is not one argument used twice

Case classes

A book

case class Book(title: String, pages: Int)

What you get

PieceDetail
FieldsA case-class parameter is a val
FactoryBook("Dune", 412) calls apply on the companion
==Compares the fields. Two books with the same fields are equal
eqTrue only for the same instance
copybook.copy(pages = 500) changes one field and keeps the rest
A plain classDoes not get field equality, copy, or the factory

Pattern matching

First page, or zero

pages match {
  case Nil => 0
  case h :: _ => h
}

Match rules

FactDetail
Expressionmatch produces a value. Each case is a branch
case _The fallback. It matches anything left
Lowercase nameA new variable, so that case always matches
Capital nameMatches an existing value, such as None or a singleton
sealedThe compiler warns when a case of a sealed type is missing
enumA Scala 3 sealed set of cases. ordinal starts at 0. A missed case throws MatchError

For-comprehensions

Keep the long books

for (n <- pages if n > 200) yield n

How for translates

PieceBecomes
yieldA new collection of the results
No yieldThe result is Unit. The values are thrown away
ifA filter, via withFilter
One generatormap
Several generatorsflatMap, then map on the last one
OptionThe whole for is None as soon as one generator is None

Types

A type after the name

val title: String = "Dune"

Type rules

FactDetail
AnyThe top type. Nothing is the bottom type, and Nil is a List[Nothing]
List[+A]Covariant. A List[String] is a List[Any]
ArrayInvariant. An Array[String] is not an Array[Any]
== on arraysArray(1) == Array(1) is false. == does not compare the elements
sameElementsTrue when two arrays hold equal values in the same order
Int overflowInt.MaxValue + 1 wraps to Int.MinValue. There is no overflow error

Objects and traits

A singleton

object Shelf {
  def size: Int = 1
}

Sharing behavior

FormDetail
objectA singleton. The body runs once
CompanionAn object with the class name. It can see the private fields
traitMethods a class can mix in. A class extends one class and any number of traits
ClashIf two traits define the same method, the one mixed in last wins
givenA Scala 3 context value the compiler may insert. using asks for it
implicitThe Scala 2 spelling of given and using

Interview traps

Traps worth memorising

TrapWhat happensPrefer
val nums = Array(1, 2) then nums(0) = 9val stops a new binding. The array itself can still changeA List or a Vector when the values must stay put
Array(1) == Array(1)false. Array equality is identitysameElements
Nil.headThrows NoSuchElementExceptionheadOption
None.getThrows NoSuchElementExceptiongetOrElse
pages(1) as the first pageIndex 0 is the first elementpages.head or pages(0)
pages :+ 90 in a loopEach append copies the list:: to prepend, or a Vector
case head =>A lowercase name is a new variable, so the case always matchesA capital name to match an existing value
"Book $title"The dollar stays as texts"Book $title"
List(1, 2) == Vector(1, 2)true. Sequences compare by elements, not by classCompare types with isInstanceOf when the class matters
0.1 + 0.2 == 0.3falseA tolerance, or integers for exact money
A for with no yieldThe result is Unityield when you need the values
Int.MaxValue + 1Wraps to Int.MinValueA Long when the magnitude matters

Empty stays empty

pages.headOption.getOrElse(0)

Compare the elements

Array(1, 2).sameElements(Array(1, 2))

How to use this page: bind names with val, use Option instead of null, and match a sealed type. Compare arrays with sameElements.