Scala
Updated: May 22, 2026Categories: Languages
Printed from:
Scala Cheatsheet
Language Overview
Scala is a modern, multi-paradigm programming language that combines object-oriented and functional programming paradigms. Designed to express common programming patterns concisely, Scala runs on the Java Virtual Machine (JVM) and is fully interoperable with Java. Scala 3 (Dotty) introduced a redesigned type system, new indentation-based syntax, and many language improvements while retaining strong interoperability with Scala 2.13.
Key Features:
- Statically typed with powerful type inference
- Supports both object-oriented and functional programming
- Runs on JVM with seamless Java interoperability; also targets JavaScript (Scala.js) and native code (Scala Native)
- Immutability and functional programming constructs
- Concise syntax with an advanced type system (union and intersection types, opaque types, given/using, enums, extension methods)
Basic Syntax
Hello World
Scala
1234567891011// Scala 3 (optional braces / top-level definitions) @main def hello(): Unit = println("Hello, Scala!") // Scala 2 / Scala 3 (braces style) object HelloWorld { def main(args: Array[String]): Unit = { println("Hello, Scala!") } }
Comments
Scala
123456789101112// Single-line comment /* Multi-line comment */ /** * ScalaDoc comment * Used for generating documentation */
Data Types
Primitive Types
Scala
123456789101112131415// Numeric Types val byte: Byte = 127 val short: Short = 32767 val int: Int = 2147483647 val long: Long = 9223372036854775807L val float: Float = 3.14f val double: Double = 3.14159 // Boolean and Character val bool: Boolean = true val char: Char = 'A' // String val str: String = "Scala"
Collection Types
Scala
12345678910111213141516// Immutable Collections val list: List[Int] = List(1, 2, 3) val vector: Vector[Int] = Vector(1, 2, 3) // preferred general-purpose immutable seq val set: Set[String] = Set("a", "b", "c") val map: Map[String, Int] = Map("one" -> 1, "two" -> 2) // Mutable Collections import scala.collection.mutable val mutableList = mutable.ListBuffer(1, 2, 3) val mutableSet = mutable.Set("a", "b") val mutableMap = mutable.Map("one" -> 1) // ArraySeq replaces WrappedArray (since 2.13) val arr: scala.collection.immutable.ArraySeq[Int] = scala.collection.immutable.ArraySeq(1, 2, 3)
Variables and Constants
Scala
1234567891011121314// Immutable variable (recommended) val immutableVar: Int = 42 // Mutable variable var mutableVar: String = "Hello" mutableVar = "World" // Type inference val inferredInt = 10 // Type is inferred as Int val inferredString = "Scala" // Type is inferred as String // Lazy initialization lazy val expensive: Int = computeSomething()
Operators
Arithmetic Operators
Scala
123456val sum = 5 + 3 // Addition val diff = 10 - 4 // Subtraction val prod = 3 * 6 // Multiplication val div = 15 / 3 // Division val mod = 10 % 3 // Modulus
Comparison Operators
Scala
1234567val isEqual = (5 == 5) // Equality val isNotEqual = (5 != 3) // Inequality val greaterThan = 10 > 5 // Greater than val lessThan = 3 < 7 // Less than val greaterOrEqual = 5 >= 5 // Greater or equal val lessOrEqual = 3 <= 4 // Less or equal
Logical Operators
Scala
1234val andOp = true && false // Logical AND val orOp = true || false // Logical OR val notOp = !true // Logical NOT
Control Structures
Conditional Statements
Scala
123456789101112// If-Else (expression) val label = if x > 0 then "positive" else if x < 0 then "negative" else "zero" // Pattern Matching val result = someValue match case 1 => "One" case 2 => "Two" case _ => "Other"
Loops
Scala
123456789101112131415// For Loop (Scala 3 optional-braces syntax) for i <- 1 to 5 do println(i) // For Loop with Guard for i <- 1 to 10 if i % 2 == 0 do println(i) // While Loop var x = 0 while x < 5 do println(x) x += 1 // Note: Scala 3 removed `do { ... } while (...)`. // Emulate with a while loop and a flag, or use recursion.
Functions
Basic Function Definition
Scala
1234567891011def add(a: Int, b: Int): Int = a + b // Function with default parameter def greet(name: String = "World"): String = s"Hello, $name!" // Multiple parameter lists (currying) def multiply(x: Int)(y: Int): Int = x * y // Context parameters (Scala 3: `using` replaces `implicit`) def render(msg: String)(using ec: scala.concurrent.ExecutionContext): Unit = ???
Lambda Functions (Anonymous Functions)
Scala
1234val square = (x: Int) => x * x val numbers = List(1, 2, 3, 4) val squared = numbers.map(square)
Higher-Order Functions
Scala
1234def operate(f: (Int, Int) => Int, x: Int, y: Int): Int = f(x, y) val sum = operate(_ + _, 5, 3) // Returns 8
Extension Methods (Scala 3)
Scala
12345extension (s: String) def shout: String = s.toUpperCase + "!" "hello".shout // "HELLO!"
Object-Oriented Programming
Classes and Objects
Scala
1234567891011// Class definition class Person(val name: String, var age: Int): def introduce(): String = s"Hi, I'm $name and I'm $age years old" // Creating an object (Scala 3 makes `new` optional via `apply`, // but `new` is still valid and required for non-case classes without apply) val john = Person("John", 30) // Case Class (immutable, with automatic methods) case class Point(x: Int, y: Int)
Traits and Enums
Scala
12345678910111213141516171819trait Logger: def log(message: String): Unit class ConsoleLogger extends Logger: def log(message: String): Unit = println(message) // Trait with parameters (Scala 3) trait Greeter(prefix: String): def greet(name: String): String = s"$prefix, $name" // Enums (Scala 3) replace most uses of sealed trait + case object hierarchies enum Color: case Red, Green, Blue // Algebraic Data Types via enums enum Shape: case Circle(radius: Double) case Rectangle(width: Double, height: Double)
Union and Intersection Types (Scala 3)
Scala
123456def describe(x: Int | String): String = x match case i: Int => s"int $i" case s: String => s"string $s" type ReadWrite = Readable & Writable
Opaque Types (Scala 3)
Scala
123456object ids: opaque type UserId = Long object UserId: def apply(l: Long): UserId = l extension (id: UserId) def value: Long = id
Error Handling
Try / Success / Failure
Scala
12345678import scala.util.{Try, Success, Failure} def divide(a: Int, b: Int): Try[Int] = Try(a / b) divide(10, 0) match case Success(value) => println(s"Result: $value") case Failure(exception) => println(s"Error: ${exception.getMessage}")
Option for Null Safety
Scala
123456val someValue: Option[Int] = Some(42) val noneValue: Option[Int] = None someValue.map(_ * 2) // Some(84) noneValue.getOrElse(0) // 0
Either for Typed Errors
Scala
12345def parseInt(s: String): Either[String, Int] = s.toIntOption.toRight(s"not an int: $s") parseInt("42").map(_ + 1) // Right(43)
File I/O
Scala
12345678910111213import scala.io.Source import scala.util.Using import java.io.{File, PrintWriter} // Reading a file (auto-closes resource) val lines: List[String] = Using.resource(Source.fromFile("example.txt"))(_.getLines().toList) // Writing to a file Using.resource(new PrintWriter(new File("output.txt"))) { writer => writer.write("Hello, Scala!") }
Functional Programming Concepts
Immutable Collections
Scala
123456val numbers = List(1, 2, 3, 4, 5) val doubled = numbers.map(_ * 2) val filtered = numbers.filter(_ % 2 == 0) val reduced = numbers.reduce(_ + _) val folded = numbers.foldLeft(0)(_ + _)
For-Comprehensions
Scala
123456val result = for x <- List(1, 2, 3) y <- List(4, 5, 6) yield x * y
Given / Using (Scala 3 contextual abstractions)
Scala
12345678910trait Show[A]: def show(a: A): String given Show[Int] with def show(a: Int): String = a.toString def print[A](a: A)(using s: Show[A]): Unit = println(s.show(a)) print(42) // uses given Show[Int]
Concurrent Programming
Futures
Scala
12345678910import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global val futureCalculation: Future[Int] = Future { Thread.sleep(1000) 42 } futureCalculation.map(_ * 2)
Modern functional-effect libraries (Cats Effect 3, ZIO 2) are commonly used for production-grade concurrency, resource safety, and structured fibers.
Common Libraries and Frameworks
Standard Library
scala.collection: Immutable and mutable collectionsscala.concurrent: Futures and parallel processingscala.io/scala.util.Using: File and I/O operations with resource management
Popular Third-Party Libraries
- Akka / Pekko: Actors, streams, and distributed computing (Pekko is the Apache fork after Akka's license change)
- Play Framework: Web application framework
- Apache Spark: Big data processing
- Cats and Cats Effect: Functional programming and effect system
- ZIO: Effect system with built-in concurrency, streams, and dependency injection
- http4s, Tapir, ZIO HTTP: HTTP servers and endpoint description
- Doobie, Slick, Quill: Database access
- Circe, uPickle, jsoniter-scala: JSON
Tooling
Build and Dependency Management
- sbt (Scala Build Tool) — the de facto standard
- Mill — alternative Scala build tool
- Maven and Gradle — also supported
- Coursier — artifact fetcher and Scala application launcher (used by
cs setup)
Versions and Compiler
- Scala 3.x is the current major release line and recommended for new projects.
- Scala 2.13 remains widely used and is binary-compatible with Scala 3 dependencies.
- Scala 2.12 / 2.11 / 2.10 are legacy.
- Scala 3 ships with the Dotty compiler; Scala 2 uses scalac.
Testing
- ScalaTest: Popular testing framework
- MUnit: Lightweight, fast test framework
- Specs2: BDD-style testing
- ScalaCheck: Property-based testing
- weaver-test: Effect-friendly testing for Cats Effect / ZIO
Best Practices
Code Style
- Prefer immutability (
val, immutable collections) - Use pattern matching and
matchexpressions - Leverage type inference, but annotate public APIs
- Write pure functions; isolate side effects
- Use
Option/Either/Tryinstead ofnulland thrown exceptions - In Scala 3, prefer
enumfor ADTs andgiven/usingoverimplicit
Performance Tips
- Use
lazy valfor deferred computation - Prefer
Vector/ArraySeqfor general-purpose immutable sequences - Specialize hot loops with primitive arrays where needed
- Use
Usingfor safe resource management - Be mindful of parallel collections (
.parmoved to a separate module in 2.13+)
Resources for Further Learning
- "Programming in Scala" by Martin Odersky, Lex Spoon, Bill Venners, and Frank Sommers
- Scala Documentation: https://docs.scala-lang.org
- Scala 3 Book: https://docs.scala-lang.org/scala3/book/
- Scala Exercises: https://www.scala-exercises.org
- "Functional Programming in Scala" (Red Book) by Paul Chiusano and Rúnar Bjarnason
Continue Learning
Discover more cheatsheets to boost your productivity