Top 10 Scala scenario questions
Try each one yourself first, then open the model answer.
1. A recursive function overflows the stack on large input. What do you do?
Show answerHide answer
Rewrite it to be tail-recursive and annotate it with @tailrec so the compiler verifies it, or use a fold.
2. Several operations can each fail. How do you compose them without nested try blocks?
Show answerHide answer
Use Either or Try in a for-comprehension, so the first failure short-circuits and carries its reason.
3. Futures that should run in parallel run one after another. Why?
Show answerHide answer
They were created inside the for-comprehension. Create them first, then combine them.
4. Code uses Option.get and crashes. What is the better approach?
Show answerHide answer
Use getOrElse, map, fold or pattern matching to handle the empty case.
5. Adding a new case to a sealed trait should not be forgotten. How does the compiler help?
Show answerHide answer
Pattern matches on sealed types are checked for exhaustiveness. Enable warnings and treat them as errors.
6. A Spark job is slow with one task running far longer than others. What is happening?
Show answerHide answer
Data skew. Check key distribution, salt heavy keys, use broadcast joins for small tables or enable adaptive query execution.
7. Collecting a large dataset crashes the driver. What do you do instead?
Show answerHide answer
Avoid collect. Aggregate on the cluster, write results to storage, or take a small sample.
8. Shared mutable state causes bugs across threads. What is the idiomatic fix?
Show answerHide answer
Prefer immutable data and pure functions, and isolate necessary state with atomic references or an effect or actor library.
9. A blocking database call inside Futures starves the application. How do you solve it?
Show answerHide answer
Run blocking work on a dedicated thread pool and keep the default pool for CPU work.
10. Implicit values make behaviour hard to trace. How would you keep it manageable?
Show answerHide answer
Use implicits or givens sparingly, place instances in companion objects, give them clear types and rely on IDE tools to show what is applied.
