Pair your devices with a code and playback position follows you: pause on this device, hit resume on the other. Position is saved to the site every minute and on pause.
Open this panel on your other device and enter the same code.
Starts this lesson and continues through 5 more to the end of the course.
You write PySpark daily; the team you would lead has Scala jobs too. Nobody needs you to be its best Scala programmer. They need you to read a Scala PR, spot what breaks in production, and say why.
What the posting is really asking. "Solutions using Apache Spark, Scala, and Python" plus "conduct code reviews" plus "best practices in coding" means: you can review Scala you did not write, you know which Scala version the cluster demands, and you can explain a compiler error to a junior. The Dataset API, encoders and closures are lesson 2.
Every Scala snippet was run on 2026-11-22 in
spark-shell4.3.0 (Scala 2.13.18, Java 17.0.18); output is shown as comments. Scala 3 and sbt snippets are copied from docs, marked not executed.
From the Spark docs index for each line (verified 2026-11-22):
| Spark 3.5 line (3.5.10 docs) | Spark 4.3.0 (latest docs) | |
|---|---|---|
| Scala | 2.12 / 2.13 | 2.13 only |
| Java | 8 / 11 / 17 | 17 / 21 / 25 |
| Python | 3.8+ | 3.11+ |
Quick-start scalaVersion |
2.12.18 |
2.13.18 |
| Maven artifact | spark-sql_2.12 |
spark-core_2.13 / spark-sql_2.13 |
The 4.3.0 index: "it is necessary for applications to use the same version of Scala that Spark was compiled for. Since Spark 4.0.0, it's Scala 2.13." The building page: "support for Scala 2.12 was removed in Spark 4.0.0". The 4.0.0 release notes list SPARK-45314 (drop Scala 2.12) and SPARK-45315 (drop JDK 8/11, JDK 17 default). Java 25 came in 4.2.0 (SPARK-51167); 4.3.0 dropped Python 3.10 (SPARK-56889). Both lines still ship: the news page dates 3.5.10 at Nov 22, 2026.
⚠️ Scala 3: the Spark docs are silent. "Scala 3" appears zero times in the 4.3.0 index, building
page, quick start, SQL getting-started guide, and the 4.0.0, 4.2.0 and 4.3.0 release notes. On
Maven Central
spark-sql_2.13 lists 4.3.0, spark-sql_2.12 stops at 3.5.10, and spark-sql_3 returns 404. Scala's
interoperability guide
says Scala 3 can depend on 2.13 binaries but "cannot expand Scala 2 macros"; I could not verify
whether Spark's encoders work from Scala 3. The defensible answer: Spark 4 is a Scala 2.13
platform; Scala 3 is not a documented target.
val x = 1 + 1
x = 3 // error: reassignment to val
val a = { println("val: evaluated now, once"); 42 }
def b = { println("def: evaluated on every call"); 42 }
lazy val c = { println("lazy val: evaluated on first use, once"); 42 }
a + a // prints nothing more
b + b // prints the def line twice
c + c // prints the lazy val line once
var y = 1; y = 3 // compiles
val size = if (y > 2) "big" else "small" // if/else returns a value
def fac(n: Int) = if (n <= 1) 1 else n * fac(n - 1)
// error: recursive method fac needs result type
The tour: "Referencing a value does not re-compute
it"; a method's "last expression in the body is the method's return value", and return "is rarely
used". The 2.13 spec:
a lazy value "is initialized the first time it is accessed (which might never happen at all)". The
Scala 3 book: "You should always
create a variable with val, unless there's a reason you need a mutable variable", and if/else
returns a value.
Types go after the name and are usually inferred,
except a recursive method's result (above) and method parameters. The tour recommends "that you make
the type explicit for any APIs that will be exposed to users of your code" — so in review, public
defs get a return type.
sealed trait Event
case class Click(userId: String, x: Int, y: Int) extends Event
case class Purchase(userId: String, amount: BigDecimal) extends Event
case object Heartbeat extends Event
val c1 = Click("u1", 3, 4)
c1 == Click("u1", 3, 4) // true — compared by structure
c1.copy(x = 99) // Click(u1,99,4)
c1.x = 5 // error: reassignment to val
def describe(e: Event): String = e match {
case Click(u, x, y) if x < 0 || y < 0 => s"$u clicked off-screen"
case Click(u, _, _) => s"$u clicked"
case Purchase(u, amt) => s"$u paid $amt"
case Heartbeat => "heartbeat"
}
A case class gives you public val fields, an
apply (no new), structural equality and copy.
sealed is the part reviewers miss. A sealed trait "can be extended only in the same file as its
declaration", so "the compiler checks that the cases of a match expression are exhaustive"
(tour: pattern matching). I removed the
Heartbeat case and compiled it:
WARNING: match may not be exhaustive.
It would fail on the following input: Heartbeat
Failure(scala.MatchError: Heartbeat ...)
⚠️ It is a warning; the failure is a runtime MatchError on whichever row hits the missing case.
Worse, spark-shell did not print the warning in my run — I saw it only by compiling the same code
through the compiler's ToolBox. The
compiler options page documents
-Werror (or -Xfatal-warnings): "Fail the compilation if there are any warnings." Ask whether the
build sets it.
val countries = Map("u1" -> "PH", "u2" -> "US")
countries.get("u1") // Some(PH)
countries.get("u9").map(_.toLowerCase).getOrElse("unknown") // unknown
countries.get("u9").get // java.util.NoSuchElementException: None.get
Option(System.getenv("NO_SUCH_VAR_STL")) // None — wraps a Java null
Some(null: String).map(_.length) // NullPointerException
import scala.util.Try
def parseAmount(s: String): Try[BigDecimal] = Try(BigDecimal(s.trim))
parseAmount(" 12.50 ") // Success(12.50)
parseAmount("twelve") // Failure(java.lang.NumberFormatException: ...)
// validate(s): Either[String, BigDecimal] wraps parseAmount; Left carries the error message
validate("-3").map(_ * 2) // Left(negative amount -3) — map skips a Left
for { a <- validate("10"); b <- validate("2.5") } yield a + b // Right(12.5)
| Type | Cases | Use when | API docs |
|---|---|---|---|
Option[A] |
Some / None |
value may be absent | get throws NoSuchElementException if empty |
Try[A] |
Success / Failure |
code can throw | "only non-fatal exceptions are caught" |
Either[L, R] |
Left / Right |
typed error | "Left is used for failure"; "right-biased" |
Option(null) is None; Some(null) holds a null — at a Java boundary use Option(...). The style
(Scala 3 book):
"Functional methods don't throw exceptions; instead they return values like Option, Try, or Either".
Immutable collections "never change": operations "return a new collection and leave the old
collection unchanged" (collections overview);
"none of the methods on List mutate the list"
(Scala 3 book).
val orders = List(("u1","PH",20.0), ("u2","US",5.0), ("u1","PH",7.5), ("u3","US",12.0))
orders.filter(_._3 >= 7) // List((u1,PH,20.0), (u1,PH,7.5), (u3,US,12.0))
orders.map(_._3).foldLeft(0.0)(_ + _) // 44.5
orders.groupBy(_._2) // HashMap(PH -> List(...), US -> List(...))
List(1, 2) += 3 // error: value += is not a member of List[Int]
// a for-comprehension is sugar for withFilter / map / flatMap
val viaFor = for { (user, country, amt) <- orders if country == "US" } yield user -> amt * 2
val viaCalls = orders.withFilter { case (_, c, _) => c == "US" }.map { case (u, _, a) => u -> a * 2 }
viaFor == viaCalls // true
"Every datatype that supports the operations withFilter, map, and flatMap (with the proper
types) can be used in sequence comprehensions"
(tour) — hence for over Either above.
Now the confusion that bites reviewers. Spark reuses these names on a different machine:
val local = List(1, 2, 3).map { n => println(s"local map sees $n"); n * 2 }
// local map sees 1 / 2 / 3 <- printed immediately
val ds = List(1, 2, 3).toDS().map { n => println(s"spark map sees $n"); n * 2 }
// (nothing printed) ds: [value: int]
ds.collect()
// spark map sees 1 / 2 / 3 <- only now
orders.groupBy(_._2).getClass.getName // scala.collection.immutable.HashMap
df.groupBy("country").getClass.getName // org.apache.spark.sql.classic.RelationalGroupedDataset
List.map / groupBy |
Dataset.map / groupBy |
|
|---|---|---|
| Runs | immediately, in this JVM | when an action fires — "Datasets are 'lazy'" (Dataset API) |
| Returns | a new in-memory collection | a plan; groupBy returns a grouping object, not data |
| Extra parameter | none | map[U](func: (T) => U)(implicit arg0: Encoder[U]) |
In review: after .collect(), every map/filter/groupBy in the chain is single-JVM Scala on the
driver. Same names, no error, no parallelism. Lazy evaluation is
PS0 lesson 2.
applyclass MaxAmount(limit: Double) extends Validator with Audited.object — "a class that has exactly one instance. It is created lazily when it is referenced"
(singleton objects). Confirmed: a
println in an object body ran only at first access. What that means on a cluster is lesson 2.static members in Java are modeled as ordinary members of a companion object."apply — Money("12.50") is Money.apply("12.50"), and List(10, 20, 30)(1) is
List.apply(10, 20, 30).apply(1); each pair printed equal results. With a private constructor,
new Money(5) did not compile.A contextual parameter is one the
compiler fills in: "Parameter lists starting with the keyword using (or implicit in Scala 2) mark
contextual parameters."
case class Tenant(id: String)
def tableName(base: String)(implicit t: Tenant): String = s"${t.id}_$base"
tableName("orders") // error: could not find implicit value for parameter t: Tenant
implicit val current: Tenant = Tenant("acme")
tableName("orders") // acme_orders
tableName("orders")(Tenant("globex")) // globex_orders — you can always pass it explicitly
Scala 3 spelling, same tour page (not executed):
def max[A](x: A, y: A)(using comparator: Comparator[A]): A, with instances declared
given Comparator[Int] with .... Spark 4 code is Scala 2.13, so you will read implicit.
Where a Spark engineer meets them: import spark.implicits._. The
SQL guide: "This import is needed to
use the $-notation" and "Encoders for most common types are automatically provided by importing
spark.implicits._". SQLImplicits
declares implicit class StringToColumn, a custom
string interpolator. Compiled
without the import: value $ is not a member of StringContext and Unable to find encoder for type String. An implicit Encoder[String] is needed.... Encoders are lesson 2.
⚠️ spark-shell already has the import in scope — $"id" and .toDS() compiled without it. Code
pasted from a shell into a job will not compile until you add it.
Both columns were run; both printed PH 2750 2 / US 1200 1.
| Python (3.14) | Scala (2.13) |
|---|---|
def double(n: int) -> int: return n * 2 |
def double(n: Int): Int = n * 2 |
@dataclass(frozen=True) class Order: ... |
case class Order(user: String, country: String, amount: Double) |
d.get(k) → value or None |
d.get(k) → Some(v) or None |
[n * 2 for n in xs if n > 1] |
for (n <- xs if n > 1) yield n * 2 |
lambda n: n + 1 |
(n: Int) => n + 1 |
"big" if limit > 2 else "small" |
if (limit > 2) "big" else "small" |
match e: case Order(user=u): ... |
e match { case Order(u, _, _) => ... } |
result = (orders # Python
.filter(F.col("amount") >= limit)
.withColumn("amount_cents", (F.col("amount") * 100).cast("long"))
.groupBy("country")
.agg(F.sum("amount_cents").alias("cents"), F.count("*").alias("orders"))
.orderBy("country"))
The Scala version I ran is the same six lines with val result = in front and the F. prefixes
removed (import org.apache.spark.sql.functions._). What Scala adds is orders.as[Order], a typed
Dataset[Order]: "Python does not have the support for the Dataset API", and "DataFrame is simply a
type alias of Dataset[Row]"
(SQL guide).
%%, _2.13, binary compatibilityFrom the Spark quick start (not executed — no sbt in the scratch environment):
name := "Simple Project"
version := "1.0"
scalaVersion := "2.13.18"
libraryDependencies += "org.apache.spark" %% "spark-sql" % "4.3.0"
%% makes sbt "add your project's binary Scala version to the artifact name"
(sbt library dependencies), so this
resolves spark-sql_2.13. A single % with a hand-typed _2.12 is the bug to look for. The suffix
exists because "different versions of Scala can be binary incompatible, despite maintaining source
compatibility" (sbt cross-building).LinkageError" at run time
(binary compatibility).
So a _2.12 library on a Spark 4 classpath is a run-time risk the compiler will not flag.
⚠️ Not reproduced here (no 2.12 jar, no sbt).provided dependencies; these need not be bundled since they are provided
by the cluster manager at runtime"
(submitting applications).Every row was run in this lesson's session or is quoted from a doc linked above.
| Look for | Why | Ask for |
|---|---|---|
.get on an Option |
NoSuchElementException: None.get at run time |
getOrElse, map, or a match |
null, or Some(x) around a Java call |
Some(null).map(...) threw an NPE |
Option(x) |
match with no sealed base or no -Werror |
missing case is a warning, then MatchError |
seal the trait; fail on warnings |
var and scala.collection.mutable |
a helper changed its caller's mutable.Map in place; the same write on an immutable Map did not compile |
val + immutable; updated returns a copy |
return inside a lambda |
it throws: a catch { case t: Throwable } caught scala.runtime.NonLocalReturnControl and the method returned None, not Some(-1). Deprecated since Scala 3.2.0 |
find |
% with _2.12; map/groupBy after .collect() |
binary mismatch; driver-only work | %%; stay in the Dataset |
What to tell a junior: Option, sealed traits and immutable values turn run-time failures into
compile-time ones — if the build treats warnings as errors.
match on a sealed trait misses a case. What happens at compile time and at run time?"org.apache.spark" % "spark-sql_2.12" % "4.3.0" — what are the two problems?-Werror. Run time:
scala.MatchError when that value arrives._2.12 is a different Scala major version from Spark 4's 2.13 — binary incompatible — and
spark-sql_2.12 stops at 3.5.10 on Maven Central, so 4.3.0 will not resolve. Use
%% "spark-sql" % "4.3.0", marked provided.map calls with a println inside — List, then Dataset, pausing before
collect(). Then delete a case from the sealed match and show spark-shell says nothing.map and groupBy mean one thing, so a post-collect()
chain looks normal.