Scala interview questions, from case classes to effects
Scala interview questions test how well you model data with case classes and sealed traits, use pattern matching, Option and Either instead of nulls and exceptions, and read a for-comprehension as the map and flatMap calls it really is. Mid-level rounds add implicits or Scala 3 given and using, type classes, variance and collections; senior rounds move to Futures versus effect types such as Cats Effect or ZIO, Spark jobs and keeping an sbt build healthy. Most interviews mix a short functional coding task with a conversation about code you have shipped.
By Evin JohnPublished 10 min read
Where Scala jobs are, and what the loop looks like
Scala hiring clusters in two places. Data engineering teams use it with Apache Spark, Kafka and Flink, where questions lean toward Datasets, case classes and serialization. Back-end teams in finance, streaming, ad tech and payments use it for services built on Play, http4s, Akka or Apache Pekko, Cats Effect or ZIO, where questions lean toward typed functional design and concurrency. A third, smaller group works on compilers, tooling or research code. Find out which one you are interviewing for, because a Spark team rarely asks about type class derivation and a Typelevel shop rarely asks about shuffle partitions.
- Language screenShort questions on case classes, Option, pattern matching and collections, sometimes as "what does this return?" snippets.
- Functional coding taskA small problem solved without mutation: parse and validate input, group records, or fold over a list into a summary.
- Design or code reviewModel a domain with types, review a pull request full of null checks and thrown exceptions, or explain how you would test an effectful service.
- Experience deep diveA system you built: why Scala, which libraries, what broke in production and how you handled upgrades.
Fundamentals
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is the difference between val, var, lazy val and def? | Evaluation | val is evaluated once and fixed, var can be reassigned, lazy val runs on first use and caches, def runs every time it is called |
| What does a case class give you for free? | Data types | Structural equals and hashCode, a readable toString, copy, an apply without new, and an unapply for pattern matching |
| What is a companion object? | Objects | A singleton with the same name as a class, in the same file, that can see its private members; the usual home for factory methods and instances |
| Trait or abstract class? | Composition | A class can mix in many traits but extend one class; abstract classes were needed for constructor parameters before Scala 3 allowed them on traits |
| Why prefer Option to null? | Safety | The type says a value may be missing, so callers must handle None; map, flatMap and getOrElse replace scattered null checks |
| What does it mean that if and match are expressions? | Style | They return values, so you assign their result instead of mutating a variable in each branch |
| Explain Any, AnyVal, AnyRef, Nothing and Null. | Type hierarchy | Any is the top; AnyVal covers value types and AnyRef reference types; Nothing is a subtype of everything, which is why throw fits any expected type |
| List, Vector or Array? | Collections | List is an immutable linked list, quick at the head; Vector gives effectively constant indexed access and appends; Array is the mutable JVM array |
| What does sealed do on a trait? | Modeling | All subtypes must live in the same file, so the compiler knows every case and warns when a match misses one |
| What is the difference between == and eq? | Equality | == calls equals and handles null safely; eq compares references, which you rarely want with case classes |
sealed trait Payment
final case class Card(last4: String, amountCents: Long) extends Payment
final case class BankTransfer(iban: String, amountCents: Long) extends Payment
case object Voucher extends Payment
def fee(p: Payment): Long = p match {
case Card(_, amount) if amount >= 100_000 => amount / 100 // 1% on large card payments
case Card(_, amount) => amount * 2 / 100 // 2% otherwise
case BankTransfer(_, _) => 50
case Voucher => 0
}
fee(Card("4242", 250_000)) // 2500
fee(Card("4242", 10_000)) // 200
fee(Voucher) // 0
// Delete the Voucher case and the compiler warns that the match is not exhaustive.Errors, for-comprehensions and folds
Interviewers often hand you a for-comprehension and ask what it compiles to. Each arrow except the last becomes a flatMap, the last becomes a map, and an if guard becomes withFilter. Once you say that, questions about why a for-comprehension over Either stops at the first error, or why mixing Option and List in one comprehension fails to type-check, answer themselves.
final case class Signup(email: String, age: Int)
def parseEmail(s: String): Either[String, String] =
if (s.contains("@")) Right(s.trim.toLowerCase) else Left(s"bad email: $s")
def parseAge(s: String): Either[String, Int] =
s.toIntOption.filter(_ >= 18).toRight(s"bad age: $s")
def signup(email: String, age: String): Either[String, Signup] =
for {
e <- parseEmail(email)
a <- parseAge(age)
} yield Signup(e, a)
// same as: parseEmail(email).flatMap(e => parseAge(age).map(a => Signup(e, a)))
signup("Ana@Example.com", "34") // Right(Signup(ana@example.com,34))
signup("nope", "x") // Left(bad email: nope), stops at the first error- Option, Either or Try: which one when? Option when absence is normal and needs no reason, Either when the caller needs to know what went wrong, Try when wrapping code that throws, such as a Java library call.
- How would you report every validation error, not only the first? Either short-circuits by design. Collect errors yourself, or use an accumulating type such as Validated in Cats or ZIO's validation helpers.
- foldLeft versus foldRight? foldLeft walks from the start with an accumulator and is stack safe on List; foldRight on a long List can be heavier. Show foldLeft building a Map of counts.
- What does @tailrec do? It asks the compiler to confirm a recursive call is in tail position, so it compiles to a loop; if not, compilation fails rather than risking a stack overflow at run time.
- What is a by-name parameter? A parameter written
=> Athat is evaluated each time it is used, not before the call. It is how getOrElse avoids computing a default you do not need. - What is currying, and why do Scala APIs use several parameter lists? It helps type inference flow from the first list to the second, allows trailing block syntax, and keeps implicit or using parameters in their own list.
- map versus flatMap on a collection? map keeps one output per input; flatMap flattens a collection of results, which is why it chains computations that each return a container.
- How do you avoid mutation inside a loop? Use map, filter, collect, groupBy, foldLeft or groupMapReduce, and keep any needed mutable builder local to one function.
Implicits, given and using, type classes and variance
This is where Scala interviews separate people who use the language from people who can design with it. Scala 2 uses implicit values, parameters and classes; Scala 3 splits these into given instances, using clauses, extension methods and explicit Conversion instances, so each use reads differently. A type class question is the common way in.
trait Show[A] {
def show(a: A): String
}
object Show {
given Show[Int] = a => s"Int($a)"
given [A](using s: Show[A]): Show[List[A]] =
as => as.map(s.show).mkString("[", ", ", "]")
}
def render[A](a: A)(using s: Show[A]): String = s.show(a)
render(List(1, 2, 3)) // [Int(1), Int(2), Int(3)]
// render("hi") does not compile: no given Show[String] is in scope.
// Scala 2 shape: implicit val intShow: Show[Int] = ...
// implicit def listShow[A](implicit s: Show[A]): Show[List[A]] = ...| Question | What it tests | What a strong answer shows |
|---|---|---|
| Where does the compiler look for an implicit or given? | Resolution | The local scope and imports first, then the implicit scope of the types involved, which includes their companion objects |
| What is a type class, and why not use inheritance? | Design | Behavior attached to a type from outside it, so you can add Show or Encoder to types you do not own |
| What do +A and -A mean? | Variance | List[+A] is covariant, so a List[Cat] is a List[Animal]; function inputs are contravariant, so a handler of Animal can stand in for a handler of Cat |
| Why can a covariant class not take A as a method parameter? | Variance rules | It would let you insert a Dog into a List[Cat] viewed as List[Animal]; the fix is a lower bound such as B >: A |
| What are upper and lower type bounds? | Bounds | A <: Animal restricts to subtypes; B >: A widens to supertypes, as in List's prepend |
| Why are implicit conversions discouraged? | Readability | They change types silently and hide bugs; Scala 3 asks for a Conversion instance and a language import to make them explicit |
| What is new in Scala 3 for everyday code? | Scala 3 | enums, given and using, extension methods, opaque types, union and intersection types, trait parameters and optional braces |
| What is an opaque type for? | Modeling | A distinct type such as UserId over a String with no runtime wrapper, so ids cannot be mixed up |
Concurrency: Futures and effect types
A classic senior question shows two for-comprehensions over Futures and asks which one runs in parallel. A Future starts running as soon as it is created, so where you create it decides whether work overlaps.
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
val a = Future { Thread.sleep(500); 1 } // starts now
val b = Future { Thread.sleep(500); 2 } // starts now, alongside a
val together = for { x <- a; y <- b } yield x + y // about 0.5 s
val oneAfterAnother = for {
x <- Future { Thread.sleep(500); 1 }
y <- Future { Thread.sleep(500); 2 } // created only after the first one finishes
} yield x + y // about 1 s
Await.result(together, 2.seconds) // 3; block like this only at the edge or in tests- Why is Thread.sleep or a blocking JDBC call inside a Future a problem? It ties up a thread from a pool sized for CPU work. Use a separate pool for blocking calls, or the blocking helpers your effect library provides.
- How does an IO from Cats Effect or ZIO differ from a Future? It is a description that runs only when executed, so it can be retried, raced, cancelled and composed safely; a Future is already running and cannot be cancelled.
- What is an ExecutionContext? The thread pool a Future's callbacks run on. Know why importing the global one everywhere can surprise you under load.
- What problems do actors solve? Message passing to an actor that owns its state, which avoids locks. Mention that Akka changed its licence in 2022 and that Apache Pekko is an open fork many teams moved to; check what the team uses.
- How would you limit a service to ten concurrent calls to a partner API? A semaphore or bounded parallel traversal in your effect library, or a bounded queue, plus timeouts and retries with backoff.
Spark, sbt and production questions
- Why do Spark Datasets use case classes? The case class gives Spark a schema and an encoder, so you get typed fields and compile-time checks on top of the DataFrame optimizer.
- What causes "Task not serializable"? A closure sent to executors captures something that cannot be serialized, often the enclosing class. Move the function into an object, or copy the needed field into a local val first.
- Why does a library name end in _2.13 or _3? Scala major versions are not binary compatible, so each library is published per version and sbt picks the right one with %%.
- How would you plan a Scala 2.13 to Scala 3 migration? Check that key libraries publish for Scala 3, compile with migration warnings on 2.13 first, port macros last, and move one module at a time. Scala 3 can use most 2.13 libraries, which helps.
- How do you keep compile times reasonable? Split modules, avoid heavy implicit derivation in hot files, watch macro use, and keep the build server and incremental compilation healthy.
- How do you test functional code? Plain unit tests with ScalaTest or MUnit for pure functions, property-based tests with ScalaCheck for invariants, and test runtimes for effectful code.
- A teammate writes Scala like Java with nulls and vars everywhere. What do you do? Agree on a style guide and linters such as Scalafmt and Scalafix, review with examples, and refactor the riskiest modules first.
Fictional example
- At a ticketing company our pricing service returned null for missing discounts and threw exceptions for invalid seat maps, and the on-call log showed both reaching customers as server errors. I proposed modeling the inputs instead. Seat maps became a sealed trait with three cases, discounts became Option, and validation returned Either with a small error type. The compiler then pointed out four places where a new seat type had never been handled. We rolled it out module by module behind the same API, and I added ScalaCheck properties for the price rules. Pricing errors in production dropped to a handful a month, and each one now came with a clear reason instead of a stack trace.
A two-week Scala practice plan
- Days 1 to 3: case classes, sealed traits and pattern matching. Model a small domain such as orders and refunds and write total functions over it.
- Days 4 to 6: Option, Either and Try, then rewrite three for-comprehensions as flatMap and map by hand.
- Days 7 to 9: collections and folds: groupBy, groupMapReduce, foldLeft, and a tail-recursive function with @tailrec.
- Days 10 to 12: implicits or given and using, a small type class, and variance with a covariant container.
- Days 13 and 14: Futures versus an effect type, plus either a Spark Dataset job or an http4s or Play endpoint, depending on the team.
Data roles that use Scala will also ask about the engine itself, so read the Spark interview questions and Kafka interview questions. If you come from another JVM language, the Kotlin page is a useful comparison for null safety and coroutines.
Functional answers are easy to think and hard to say, so rehearse them out loud. Natively, an AI interview assistant for Mac and Windows, transcribes a mock round so you can check whether you explained the desugaring or only gestured at it. When practicing it can read a Scala snippet from a screenshot, give a hint or a step-by-step outline, and, with Pro or the free trial, shape suggested answers around your résumé and the job description.
Questions people ask
What are common Scala interview questions?
val versus lazy val versus def, what a case class generates, why sealed traits matter for pattern matching, Option versus Either versus Try, what a for-comprehension compiles to, how implicits or given and using work, variance, and when a Future starts running.
Is Scala 3 asked about in interviews?
Increasingly, though many codebases still run Scala 2.13. Know given and using, extension methods, enums and opaque types, and how a team would migrate a 2.13 project.
Do Scala interviews require Cats or ZIO?
Only for teams that use them. Back-end teams built on Typelevel or ZIO libraries will ask about effect types and resources; Spark teams focus on Datasets, case classes and serialization instead.
How do I prepare for a Scala coding round?
Solve small problems without mutation using case classes, pattern matching and folds, return Either for invalid input, and practice explaining each for-comprehension as flatMap and map calls out loud.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
