Scala Documentation
Functional + object-oriented on the JVM — used for big data (Apache Spark) and backends.
Scala combines object-oriented and functional programming on the JVM. It has a powerful type system, immutable collections, pattern matching and concise syntax, and it interoperates with Java libraries. Scala powers big-data tools like Apache Spark and Kafka, and backends at companies like LinkedIn and Twitter (X).
1. Introduction & Installation
- Install a JDK (17+), then Scala CLI or the full toolchain via Coursier (
cs setupinstallsscala,scala-cliandsbt). - IDEs: IntelliJ IDEA (Scala plugin) or VS Code with Metals.
- Try online at scastie.scala-lang.org.
scala-cli version
scala-cli run Hello.scala # compile + run a file
sbt new scala/scala3.g8 # create an sbt project
sbt run
@main def hello(): Unit =
println("Hello, Codify!")
Output:
Hello, Codify!
This page uses Scala 3 syntax (indentation-based blocks are optional; braces still work).
⚠️ Common error:
No main method found— mark your entry point with@main(Scala 3) or defineobject Main { def main(args: Array[String]): Unit = ... }.
2. Basic Syntax
val= immutable value (prefer it),var= mutable variable.- Types come after names:
val age: Int = 20(usually inferred). - String interpolation:
s"Hi $name",f"$price%.2f",raw"...". - Everything is an expression —
if,matchand blocks return values.
@main def run(): Unit =
val name = "Asha"
var score = 90
score += 5
println(s"$name scored $score")
println(s"Next level at ${score + 10} points")
println(f"Price: ${99.456}%.2f")
Output:
Asha scored 95
Next level at 105 points
Price: 99.46
⚠️ Common error:
Reassignment to val score— usevarif it must change (but prefer immutability).
3. Variables & Data Types
| Type | Example |
|---|---|
Int, Long |
42, 9000000000L |
Double, Float |
3.14, 2.5f |
Boolean, Char |
true, 'S' |
String |
"text" |
Unit |
"no value" (like void) |
Option[T] |
Some(value) or None — instead of null |
BigInt, BigDecimal |
arbitrary precision |
@main def run(): Unit =
val count: Int = 10
val big = 9_000_000_000L
val price = 99.5
val ok = true
val letter = 'S'
val maybeCity: Option[String] = None
println(s"$count $big $price $ok $letter")
println(maybeCity.getOrElse("unknown"))
println("42".toInt + 1)
println(7 / 2)
println(7 / 2.0)
println(9.99.toInt)
println(BigInt(2).pow(100))
Output:
10 9000000000 99.5 true S
unknown
43
3
3.5
9
1267650600228229401496703205376
⚠️ Common error: using
null— idiomatic Scala usesOption(Some/None) so "missing" values are visible in the type.
4. Operators
Operators are just methods: a + b is a.+(b). Arithmetic + - * / %, comparison == != < > <= >= (== compares values, also for strings), logical && || !, bitwise & | ^ << >>, ranges 1 to 5 and 1 until 5.
@main def run(): Unit =
println(s"${17 / 5} ${17 % 5} ${17.0 / 5}")
println(s"${5 > 3 && 2 > 1} ${"scala" == "sca" + "la"}")
println((1 to 5).toList)
println((1 until 5).toList)
println((10 to 1 by -3).toList)
println(s"${6 & 3} ${6 | 3} ${1 << 4}")
println(3.max(7))
Output:
3 2 3.4
true true
List(1, 2, 3, 4, 5)
List(1, 2, 3, 4)
List(10, 7, 4, 1)
2 7 16
7
5. Conditionals & Pattern Matching
def grade(marks: Int): String =
if marks >= 90 then "A"
else if marks >= 75 then "B"
else "C"
def describe(x: Any): String = x match
case 0 => "zero"
case n: Int if n < 0 => "negative int"
case n: Int => s"positive int $n"
case s: String => s"string of length ${s.length}"
case (a, b) => s"a pair of $a and $b"
case _ => "something else"
@main def run(): Unit =
println(grade(82))
println(describe(0))
println(describe(-5))
println(describe(42))
println(describe("scala"))
println(describe((1, "x")))
println(describe(3.14))
Output:
B
zero
negative int
positive int 42
string of length 5
a pair of 1 and x
something else
⚠️ Common error:
MatchErrorat runtime — yourmatchdidn't cover a value. Add acase _ =>or use asealedhierarchy so the compiler warns you.
6. Loops & For-Comprehensions
@main def run(): Unit =
for i <- 1 to 3 do print(s"$i ")
println()
val langs = List("scala", "java", "kotlin")
for (lang, i) <- langs.zipWithIndex do println(s"$i: $lang")
val pairs = for
x <- 1 to 3
y <- 1 to 3
if x < y
yield (x, y) // for-comprehension builds a new collection
println(pairs)
var n = 1
while n < 100 do n *= 3
println(s"n = $n")
langs.foreach(l => print(l.toUpperCase + " "))
println()
Output:
1 2 3
0: scala
1: java
2: kotlin
Vector((1,2), (1,3), (2,3))
n = 243
SCALA JAVA KOTLIN
7. Functions
def add(a: Int, b: Int = 10): Int = a + b
def sum(nums: Int*): Int = nums.sum // varargs
def applyTwice(f: Int => Int, x: Int): Int = f(f(x)) // higher-order
def multiplier(factor: Int): Int => Int = x => x * factor // returns a function
def power(base: Long, exp: Int): Long =
@annotation.tailrec
def loop(acc: Long, e: Int): Long = if e == 0 then acc else loop(acc * base, e - 1)
loop(1, exp)
@main def run(): Unit =
val square = (x: Int) => x * x // lambda
val triple = multiplier(3)
println(s"${add(5)} ${add(2, b = 3)} ${sum(1, 2, 3, 4)}")
println(s"${applyTwice(square, 3)} ${applyTwice(_ + 1, 5)} ${triple(7)} ${power(2, 40)}")
println(List(1, 2, 3).map(square))
Output:
15 5 10
81 7 21 1099511627776
List(1, 4, 9)
_ + 1 is shorthand for x => x + 1. @tailrec makes the compiler check that recursion can be turned into a loop (no stack overflow).
8. Collections
Scala's default collections are immutable — operations return new collections.
@main def run(): Unit =
val nums = List(5, 3, 8, 1, 9)
println(nums.sorted)
println(nums.filter(_ % 2 == 1))
println(nums.map(_ * 2))
println(nums.sum)
println(nums.max)
println(nums.take(2))
println(nums.foldLeft(0)(_ + _))
println(nums.partition(_ > 4))
println(nums.zip(List("a", "b", "c")))
val ages = Map("asha" -> 21, "ravi" -> 23)
val more = ages + ("neha" -> 22)
println(more("neha"))
println(more.getOrElse("john", 0))
println(more.keys.toList.sorted)
val words = "to be or not to be".split(" ").toList
println(words.groupBy(identity).view.mapValues(_.size).toMap.toList.sortBy(-_._2).head)
println(words.distinct)
println(Set(3, 1, 3, 2).size)
val buffer = scala.collection.mutable.ListBuffer(1, 2)
buffer += 3
println(buffer)
Output:
List(1, 3, 5, 8, 9)
List(5, 3, 1, 9)
List(10, 6, 16, 2, 18)
26
9
List(5, 3)
26
(List(5, 8, 9),List(3, 1))
List((5,a), (3,b), (8,c))
22
0
List(asha, neha, ravi)
(to,2)
List(to, be, or, not)
3
ListBuffer(1, 2, 3)
Other collections: Vector (fast indexed access), Array (Java array), Set, LazyList, and mutable versions in scala.collection.mutable.
⚠️ Common error:
map("missing")throwsNoSuchElementException. UsegetOrElseorget(returns anOption).
9. Object-Oriented Programming
trait Shape: // like an interface with code
def area: Double
def name: String = "shape"
case class Rect(w: Double, h: Double) extends Shape:
def area: Double = w * h
override def name = "rect"
case class Circle(r: Double) extends Shape:
def area: Double = math.Pi * r * r
class Account(val owner: String, private var balance: Double):
def deposit(amount: Double): Unit =
require(amount > 0, "Amount must be positive")
balance += amount
def current: Double = balance
override def toString = s"$owner: $balance"
object Account: // companion object (static-like members)
def empty(owner: String) = new Account(owner, 0)
enum Level:
case Beginner, Intermediate, Advanced
@main def run(): Unit =
val shapes = List(Rect(3, 4), Circle(1))
shapes.foreach(s => println(f"${s.name} ${s.area}%.2f"))
val r = Rect(3, 4)
println(r == Rect(3, 4)) // case classes compare by value
println(r.copy(h = 10))
val acc = Account.empty("Asha")
acc.deposit(500)
println(acc)
println(Level.values.toList)
Output:
rect 12.00
shape 3.14
true
Rect(3.0,10.0)
Asha: 500.0
List(Beginner, Intermediate, Advanced)
Case classes give you immutable data with equals, hashCode, toString, copy and pattern-matching support for free.
10. Advanced Concepts
Error handling with Option, Either and Try:
import scala.util.{Try, Success, Failure}
def parseAge(s: String): Either[String, Int] =
s.toIntOption match
case Some(n) if n >= 0 => Right(n)
case Some(_) => Left("age can't be negative")
case None => Left(s"'$s' is not a number")
@main def run(): Unit =
println(parseAge("21"))
println(parseAge("-3"))
println(parseAge("abc"))
Try(10 / 0) match
case Success(v) => println(v)
case Failure(e) => println(s"failed: ${e.getMessage}")
val total = for
a <- parseAge("20")
b <- parseAge("5")
yield a + b
println(total)
Right(21)
Left(age can't be negative)
Left('abc' is not a number)
failed: / by zero
Right(25)
Futures for concurrency:
import scala.concurrent.{Future, Await}
import scala.concurrent.duration.*
import scala.concurrent.ExecutionContext.Implicits.global
@main def run(): Unit =
val a = Future { Thread.sleep(100); 21 }
val b = Future { Thread.sleep(100); 21 }
val sum = for x <- a; y <- b yield x + y
println(Await.result(sum, 2.seconds))
42
Generics, given/using (implicits) and extension methods:
extension (s: String)
def shout: String = s.toUpperCase + "!"
trait Show[A]:
def show(a: A): String
given Show[Int] with
def show(a: Int) = s"Int($a)"
def describe[A](a: A)(using s: Show[A]): String = s.show(a)
@main def run(): Unit =
println("scala".shout)
println(describe(42))
SCALA!
Int(42)
Apache Spark (big data) uses Scala's functional style:
val spark = SparkSession.builder.appName("WordCount").getOrCreate()
val counts = spark.read.textFile("book.txt")
.flatMap(_.split("\\s+"))
.groupByKey(identity)
.count()
counts.orderBy($"count(1)".desc).show(10)
Also learn: sealed traits for algebraic data types, type classes, opaque types, LazyList, sbt builds, testing with ScalaTest/munit, and effect libraries like Cats Effect or ZIO.
11. Examples with Output
Example 1 — Word frequency, top 3
@main def run(): Unit =
val text = "the cat and the hat and the bat"
text.split(" ").groupMapReduce(identity)(_ => 1)(_ + _)
.toList.sortBy((w, c) => (-c, w)).take(3)
.foreach((w, c) => println(s"$w: $c"))
the: 3
and: 2
bat: 1
Example 2 — Two Sum with a Map
def twoSum(nums: Array[Int], target: Int): Option[(Int, Int)] =
val seen = scala.collection.mutable.Map[Int, Int]()
nums.indices.collectFirst(Function.unlift { i =>
val found = seen.get(target - nums(i)).map(j => (j, i))
seen(nums(i)) = i
found
})
@main def run(): Unit = println(twoSum(Array(2, 7, 11, 15), 9))
Some((0,1))
Example 3 — Recursive sum of a list with pattern matching
def total(xs: List[Int]): Int = xs match
case Nil => 0
case head :: tail => head + total(tail)
@main def run(): Unit = println(total(List(4, 8, 15, 16, 23, 42)))
108
12. Practice Problems
- Write
isPrime(n: Int): Booleanand use it withfilterto list primes below 50. - Implement FizzBuzz with pattern matching on a tuple
(n % 3, n % 5). - Model shapes with a
sealed traitand case classes; compute the total area. - Parse a list of
"name,marks"strings into case classes usingEitherfor invalid lines. - Count word frequencies in a text and print the top 5.
- Run three
Futures in parallel and combine their results. - Write an extension method
isPalindromeonString. - Install Spark and count words in a large text file.
13. Interview Questions
1. val vs var vs def?
val is an immutable value evaluated once; var is mutable; def defines a method evaluated each time it's called.
2. What is a case class?
A class for immutable data with auto-generated equals, hashCode, toString, copy, apply and pattern-matching support.
3. What is a companion object?
An object with the same name as a class in the same file; it holds factory methods and "static" members and can access the class's private members.
4. What is a trait? A reusable unit of fields and methods that classes can mix in (multiple traits allowed) — like an interface that can carry code.
5. Option, Either, Try?
Option models a value that may be missing; Either returns a success (Right) or an error value (Left); Try captures exceptions as Success/Failure.
6. What is a for-comprehension?
Syntax sugar over map, flatMap and withFilter that works for collections, Option, Future, Either and more.
7. What are implicits / given–using?
A mechanism to pass context values automatically (type-class instances, execution contexts). Scala 3 uses given to define them and using to require them.
8. What does sealed mean?
All subclasses must be in the same file, so the compiler can check pattern matches for exhaustiveness.
9. Why is immutability preferred? Immutable data is thread-safe, easier to reason about and enables safe sharing between functions.
10. Why is Scala used with Spark?
Spark is written in Scala; its functional APIs (map, filter, reduce) map naturally to distributed data processing.
14. Cheat Sheet & References
Basics
// values, strings, printing
val x = 5; var y = 10; val s = s"x = $x"; println(f"$pi%.2f")
"42".toInt; "4x".toIntOption; 42.toString; 7 / 2; 7 / 2.0
@main def run(): Unit = println("hi")
Control flow
val r = if a > b then a else b
x match { case 1 => "one"; case n if n > 1 => "many"; case _ => "other" }
for i <- 1 to 10 if i % 2 == 0 do println(i)
val sq = for i <- 1 to 5 yield i * i
while cond do step()
Collections
val l = List(1, 2, 3); 0 :: l; l :+ 4; l ++ List(5); l.head; l.tail
l.map(_ * 2); l.filter(_ > 1); l.foldLeft(0)(_ + _); l.sum; l.sorted; l.reverse
l.groupBy(_ % 2); l.zipWithIndex; l.distinct; l.take(2); l.find(_ > 1)
val m = Map("a" -> 1); m + ("b" -> 2); m.getOrElse("z", 0); m.keys; m.values
Classes and traits
case class User(name: String, age: Int)
class A(val x: Int) extends B with T { override def toString = s"A($x)" }
trait T { def f: Int; def g: Int = f * 2 }
object Utils { def helper(): Unit = () }
enum Color { case Red, Green }
Functional and errors
val f = (x: Int) => x + 1; def g(h: Int => Int) = h(1)
Option(x).map(_ + 1).getOrElse(0)
Try(risky()).toOption; Right(1).map(_ + 1); Left("err")
extension (s: String) def twice: String = s * 2
Official documentation