Skip to content
Home
Cheat Sheets
Scala
Scala Cheat Sheet
Learn Scala from the basics →
Values & Types
val name = "Ada"
Immutable value (prefer by default)
var count = 0
Mutable variable
val price: Double = 9.99
Explicit type annotation
lazy val config = load()
Computed on first use
"42".toInt / "42".toIntOption
Convert — throwing vs Option-returning
Strings
s"Hello, $name! Next year: ${age + 1}"
String interpolation
f"$price%.2f"
Formatted interpolation (printf style)
raw"C:\temp\new"
No escape processing
"""|line 1 ... |line 2""".stripMargin
Multi-line string; stripMargin removes everything up to each |
s.length / s.toUpperCase / s.trim / s.split(",")
Common string methods
Control Flow
val kind = if n > 0 then "positive" else "not positive"
if is an expression
x match { case 0 => "zero"; case n if n < 0 => "negative"; case _ => "positive" }
Pattern matching with a guard
for i <- 1 to 5 do println(i)
Loop over a range (1 until 5 excludes 5)
for x <- xs if x > 0 yield x * 2
for-comprehension producing a collection
while i < 10 do i += 1
while loop
Methods & Functions
def area(w: Double, h: Double): Double = w * h
Method
def greet(name: String = "world") = s"Hi, $name"
Default parameter
greet(name = "Ada")
Named argument
val double = (x: Int) => x * 2
Function value (lambda)
xs.map(_ * 2)
Placeholder syntax for short lambdas
Collections
List(1, 2, 3) / Vector(1, 2, 3)
Immutable sequences
Set("a", "b") / Map("a" -> 1, "b" -> 2)
Immutable set and map
xs.filter(_ > 1).map(_ * 10).sum
Transform pipeline
xs.foldLeft(0)(_ + _)
Fold to a single value
people.groupBy(_.city) / xs.sortBy(-_)
Group and sort
m.getOrElse("c", 0) / m + ("c" -> 3)
Map lookup with default / add
Classes & Types
case class Point(x: Int, y: Int)
Immutable data class with equality and copy
p.copy(y = 5)
Copy with changes
trait Shape { def area: Double }
Trait (interface with optional implementation)
enum Color { case Red, Green, Blue }
Enumeration
object Config { val port = 8080 }
Singleton object
extension (s: String) def shout = s.toUpperCase + "!"
Extension method
Handling Absence & Errors
Option(x) / Some(1) / None
Optional value instead of null
opt.map(_ + 1).getOrElse(0)
Transform or use a default
Try("x".toInt)
Success(value) or Failure(exception)
Either[String, Int] / Right(1) / Left("error")
Result with a typed error
try risky() catch { case e: NumberFormatException => 0 }
try/catch with pattern matching
Tools
scala run hello.scala
Compile and run a file (Scala CLI)
scala repl
Interactive REPL
//> using dep com.lihaoyi::upickle:4.1.0
Add a library in a Scala CLI script
sbt compile / sbt test / sbt run
Build, test, and run an sbt project
scala test .
Run tests with Scala CLI
Cookies & your privacy
We use essential cookies to keep this site working and secure.
With your permission, we'd also like to use Google Analytics cookies to understand site traffic.
We don't use advertising or social media tracking cookies, and we honor Global Privacy Control (GPC) browser signals.
Learn more in our Privacy Policy .
Your browser is sending a GPC signal, so analytics stays off even if you accept.
Accept
Reject