Scala Cheat Sheet
Scala is a hybrid functional and object-oriented programming language running on the JVM. This Scala cheatsheet provides an example-driven reference covering core syntax, collections, pattern matching, object-oriented constructs, and functional programming primitives.
Minimal Program
object Main extends App {
println("Hello, Scala")
}
Variables
var a = 10
val b = 20
val c: Int = 30
Basic Types
Int
Long
Double
Float
Boolean
Char
String
Strings
val s = "Scala"
s.length
s.toUpperCase
val name = "World"
s"Hello $name"
Operators
a + b
a - b
a * b
a / b
a % b
a == b
a != b
a > b
a < b
Control Flow
if Expression
val r = if (a > 10) "large" else "small"
match
a match {
case 1 => "one"
case 2 => "two"
case _ => "other"
}
Loops
for (i <- 1 to 5) {
println(i)
}
while (a > 0) {
a -= 1
}
Functions
def add(a: Int, b: Int): Int = {
a + b
}
add(2, 3)
Single-Expression Functions
def square(x: Int): Int = x * x
Default Parameters
def multiply(a: Int, b: Int = 2): Int = a * b
Higher-Order Functions
def apply(x: Int, f: Int => Int): Int = f(x)
Collections
List
val list = List(1, 2, 3)
list.map(_ * 2)
list.filter(_ > 1)
Vector
val v = Vector(1, 2, 3)
Set
val set = Set(1, 2, 3)
Map
val map = Map("a" -> 1, "b" -> 2)
Iteration
for (x <- list) println(x)
list.foreach(println)
Tuples
val t = (1, "a", true)
val (x, y, z) = t
Classes
class Counter {
private var value = 0
def increment(): Unit = value += 1
def get: Int = value
}
Constructors
class Point(val x: Int, val y: Int)
Case Classes
case class User(name: String, age: Int)
val u = User("A", 20)
Pattern Matching with Case Classes
u match {
case User(name, age) => name
}
Traits
trait Logger {
def log(msg: String): Unit
}
class ConsoleLogger extends Logger {
def log(msg: String): Unit = println(msg)
}
Objects (Singletons)
object Config {
val version = "1.0"
}
Companion Objects
class Factory
object Factory {
def create(): Factory = new Factory
}
Generics
class Box[T](val value: T)
val box = new Box(10)
Option
val v: Option[Int] = Some(10)
v.getOrElse(0)
Either
val r: Either[String, Int] = Right(5)
Exceptions
try {
throw new RuntimeException("fail")
} catch {
case e: Exception => e.getMessage
}
Implicits (given / using)
given intOrd: Ordering[Int] = Ordering.Int
def max[A](a: A, b: A)(using ord: Ordering[A]) =
if ord.gt(a, b) then a else b
Futures
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
val f = Future {
42
}
File I/O
import scala.io.Source
val text = Source.fromFile("file.txt").mkString