Scala interview questions: Spark API, JVM interop and serialization

Reviewed by Mark Dickie · Last updated

4 questions on this page you can answer and see marked on the spot. Go to the first one

Scala is a JVM language, and Spark's engine runs on the JVM, so Scala interview questions for Spark test how code behaves once it leaves the driver. Expect questions on closure serialization, case classes as Dataset encoders, and which Scala binary version a Spark jar was built for. Most wrong answers confuse code that runs on the driver with code that runs on an executor.

Where do Scala Spark jobs usually fail?

AreaWhat to knowTypical failure
Closure captureA lambda that reads a field of a class captures the whole enclosing instanceTask not serializable when the job is submitted
Encodersimport spark.implicits._ supplies Encoders for case classes, tuples and primitivesNo implicit Encoder compile error when the import is missing or the case class is defined inside a method
Binary versionsSpark artifacts carry a suffix such as _2.12 or _2.13 (Spark 3.x; Spark 4.x publishes only _2.13)NoSuchMethodError at runtime when the app and Spark disagree
Java collectionsScala 2.13 moves Java conversions to scala.jdk.CollectionConvertersDeprecation warnings from JavaConverters, or a null that blows up on .asScala
Option and nullOption is a Scala type, and Spark columns use SQL nullsNullPointerException or silently wrong counts when a nullable column reaches a typed lambda

How do you check a Scala Spark answer by hand?

  1. Define case class Order(id: Long, amount: Double), build a Dataset[Order] from a Seq, call .map with a typed lambda, then compare explain() output with a .select version to see where the lambda hides the logic from the optimizer.
  2. Put a logger field in a class, call rdd.map on a method that references it, and read the stack trace to find the captured reference. Then move the logic into a top-level object and rerun.
  3. For Spark 3.x, compile one snippet against spark-sql_2.12 and spark-sql_2.13, and note which imports or method signatures change. For Spark 4.x, only the _2.13 artifact exists, so compile against that one.
  4. Convert a java.util.List with scala.jdk.CollectionConverters._, then pass it a null and observe where the failure appears.

Key facts

  • Tarmac has 12 Scala interview questions on this topic, 10 of them on this page, at difficulty 1–5 of 5.
  • Tarmac tracked 261 job postings asking for Scala in November 2026.
  • Roles asking for Scala advertise a median base salary of £67,500, across 57 job postings as of November 2026.
  • Tarmac last reviewed these Scala interview questions on 3 December 2026.

At a glance

Questions10 shown · 12 in the bank
Difficulty1–5 of 5
FormatsMultiple choice, Ordering, Fill in the blank, Multiple answer, Code output, True / false, Find the bug, Short answer, Flashcard

What you'll review

  1. scala spark api

Practice questions

Try one before you open the answer. Pick an option and press Check; it's marked on the spot.

In Apache Spark's Scala API (Spark 3.x), which of the following is an action, meaning it triggers execution of the job and returns a result to the driver?#

Options

Show answer

In Spark's Scala API, rdd.count() is an action. It triggers job execution and returns the number of elements to the driver as a Long. Transformations like map, filter, and flatMap are lazy. They only build a new RDD's lineage and compute nothing until an action is called.

Why:

Spark transformations such as map, filter, and flatMap are lazy. Each one returns a new RDD and only records lineage, so nothing is computed yet. count() is an action: it makes Spark schedule and run the job across the cluster, then return a Long to the driver. That makes rdd.count() the only listed call that triggers execution.

In a minimal Scala Spark application, put these steps in the order they must happen in the code.#

Put these in order

Show answer

A minimal Scala Spark program runs in this order: build the SparkSession, read the data into a DataFrame, apply lazy transformations such as filter, run an action such as count() to execute the work, and finally call spark.stop(). Each step needs the result of the step before it. Transformations do no work until an action runs them.

Why:

Every step depends on the one before it. You can't read data without a SparkSession, so the session comes first. The DataFrame has to exist before you can filter it. filter is a lazy transformation, so no work happens until an action such as count() runs it. You stop the session only after all the work is done, because nothing can use it after spark.stop().

In Spark 3.x with Scala, to use the $"colName" column syntax and convert a local Seq with .toDF(), you must first write import spark._____._, where spark is your SparkSession instance.#

Show answer

In Spark 3.x with Scala, to use the $"colName" column syntax and convert a local Seq with .toDF(), you must first write import spark.**implicits**._, where spark is your SparkSession instance.

Why:

import spark.implicits._ brings implicit conversions into scope. These include the $ string interpolator for columns, the encoders needed for Dataset[T] of primitives and case classes, and the toDF/toDS extension methods on local Scala collections. The import has to come from a concrete SparkSession value, which is why it is written spark.implicits and not a static package import.

In Apache Spark 3.x's Scala API, which of the following Dataset/RDD methods are actions, meaning they trigger job execution right away? Select all that apply.#

Options

Pick every one that applies.

Show answer

In Spark's Scala API, count(), collect() and take(n) are actions. Each one triggers a job because it returns a concrete result to the driver. map and filter are lazy transformations. They only add steps to the execution plan and run later, when an action is called.

Why:

Spark evaluates lazily. Transformations such as filter(...) and map(...) only add steps to the logical plan or lineage and return a new Dataset or RDD. They do not compute anything. Actions return a result to the driver or write output, so they start a job. count() returns a Long, collect() returns an Array of every element, and take(5) returns an Array of the first five elements. All three force Spark to execute the plan.

Given an active SparkSession named spark (Spark 3.x, Scala API, import spark.implicits._ in scope), what does this code print?#

val words = spark.sparkContext.parallelize(Seq("a", "b", "a", "c", "a", "b"))
val counts = words.map(w => (w, 1)).reduceByKey(_ + _)
val result = counts.collect().sortBy(_._1).map { case (k, v) => s"$k=$v" }.mkString(",")
println(result)
Show answer
a=3,b=2,c=1
Why:

map turns every word into a (word, 1) pair, and reduceByKey(_ + _) adds up the values for each key: a shows up 3 times, b 2 times and c once. collect() brings the pairs back to the driver as an Array, but the order depends on how the data was partitioned and shuffled, so it is not guaranteed. The local sortBy(_._1) sorts the pairs by key so the output is always the same. mkString then joins them as a=3,b=2,c=1.

In Apache Spark 3.x's Scala API, DataFrame is defined as a type alias for Dataset[Row], so you can call df.as[Person] (with import spark.implicits._ in scope and Person a case class whose fields match the columns) to get a typed Dataset[Person].#

Options

Show answer

Yes. In Spark 3.x's Scala API, DataFrame is a type alias for Dataset[Row]. You can turn it into a typed Dataset with df.as[Person], as long as an implicit Encoder[Person] is available. Importing spark.implicits._ provides that encoder for case classes, and the columns are matched to the case class fields by name.

Why:

The org.apache.spark.sql package object contains type DataFrame = Dataset[Row]. Because of that, a DataFrame really is an untyped Dataset of generic Row objects. Calling as[T] needs an implicit Encoder[T], which spark.implicits._ derives for case classes. The call returns a Dataset[T] view of the same data, and columns are matched to fields by name.

This Spark 3.x Scala job, run on a cluster, is supposed to print how many lines contain ERROR. It always prints errors = 0, even when the input has many error lines. Which line has the bug?#

import org.apache.spark.sql.SparkSession

object CountErrors {
  def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder().appName("errs").getOrCreate()
    val lines = spark.sparkContext.textFile(args(0))
    val errorCount = spark.sparkContext.longAccumulator("errors")
    lines.map { line =>
      if (line.contains("ERROR")) errorCount.add(1)
    }
    println(s"errors = ${errorCount.value}")
    spark.stop()
  }
}
Show answer

The bug is on line 8.

Why:

The bug is on line 8, where lines.map is used. map is a lazy transformation, and this program never calls an action on the resulting RDD. Spark therefore never runs the closure, so the add(1) calls never happen and the accumulator stays at 0 when the driver prints it. The accumulator declaration on line 7 and the add(1) call on line 9 are correct. Replacing map with foreach on line 8 makes foreach, an action, run the closure on the executors, so the accumulator is updated and the count is printed correctly.

In Spark 3.x with Scala, a developer writes:#

Show answer

Inside the lambda, threshold is really this.threshold, because it is a field accessor on the enclosing class. So the closure captures this, the Pipeline instance. Spark serializes the closure to ship it to executors, but Pipeline is not Serializable and also holds a SparkSession, so the ClosureCleaner check fails with Task not serializable. The standard fix is to copy the field into a local val before the closure, for example val t = threshold; rdd.filter(_ > t). Then only the Int is captured. Other fixes are moving the value into an object, or making the class Serializable and marking the session field @transient, but the local-val copy is the usual approach.

Why:

Scala compiles a field reference inside a lambda to this.threshold, so the anonymous function closes over the outer instance. Spark has to Java-serialize task closures to send them to executors. Serializing the closure therefore drags in Pipeline, which is not serializable. Copying the field into a method-local val removes the this reference, so only a serializable primitive is captured.

In Spark 3.x with Scala, why does ds.map(x => x.copy(v = x.v + 1)) on a Dataset[CaseClass] often run slower than the equivalent ds.withColumn("v", $"v" + 1), even though both produce the same result? Name the internal mechanism involved.#

Show answer

Typed lambdas are opaque to Catalyst. To run map, Spark has to deserialize each row from the Tungsten binary format (UnsafeRow) into a JVM case-class object using the encoder's deserializer expression. It then runs the closure and serializes the result back (DeserializeToObject → MapElements → SerializeFromObject). This adds object allocation and GC pressure, and blocks optimizations such as column pruning, predicate pushdown through the map, and constant folding. Whole-stage codegen still runs, but it has to wrap the object conversion. The Column expression stays inside Catalyst, so it is optimized and compiled straight against the binary rows.

Why:

Catalyst can only optimize expressions it can see. A Scala closure is a black box to it, so the plan has to include encoder-driven conversion steps to and from objects around the lambda. Built-in Column expressions avoid those steps and work directly on UnsafeRow data.

Spark 3.x, Scala, local mode with spark.sql.shuffle.partitions left at its default and AQE disabled (spark.sql.adaptive.enabled=false). What is printed?#

import spark.implicits._
val acc = spark.sparkContext.longAccumulator("cnt")
val ds = Seq(1, 2, 3, 4).toDS().map { x => acc.add(1); x * 2 }
ds.count()
ds.collect()
println(acc.value)
Show answer
8
Why:

The Dataset is not cached, so each action re-runs the whole lineage. collect() runs the map closure on all 4 rows, which adds 4 to the accumulator. count() also has to evaluate the map: a typed map is an opaque lambda that may have side effects, so Catalyst does not prune it the way it can drop unused untyped projections. That adds another 4. Updates made inside transformations are not deduplicated across separate jobs, so the accumulator ends at 4 + 4 = 8. This is why Spark only guarantees exactly-once accumulator updates inside actions such as foreach.

Related interview questions

Job market

See scala salaries and hiring demand from live job postings.

The other 2 questions

This page shows 10 and marks what you pick. That's as far as a page can go. A free account opens the other 2 and keeps every answer. What you miss comes back until it's right: after a day, then at longer gaps.

Start with this topic

Free · the whole bank · 100 answers per 30 days, each marked with written feedback

Interview booked? Practise the job ad instead

What moved, monthly

One email a month when the bulletin comes out: what moved in the markets we track, and the new question topics we published. Confirm your address to join. Unsubscribe any time.