Scala interview questions

25 questions from the Scala course, each with the correct answer and an explanation. Try to answer before you open the answer.

Getting Started with Scala

1. Which statement about Scala is true?

  1. It combines object-oriented and functional programming with static types on the JVM
  2. It is dynamically typed
  3. It cannot call Java libraries
  4. It only runs in the browser
Show answer

Answer: It combines object-oriented and functional programming with static types on the JVM

Scala is a statically typed OOP and FP language with full Java interoperability.

Lesson: What Scala Is and Where It Is Used

2. What does %% do in an sbt dependency?

  1. Marks the dependency as optional
  2. Downloads the source code
  3. Excludes transitive dependencies
  4. Appends the Scala binary version (such as _3) to the artifact name
Show answer

Answer: Appends the Scala binary version (such as _3) to the artifact name

Scala libraries are published per Scala binary version, and %% selects the right one.

Lesson: Installing Scala: Scala CLI, sbt and the REPL

3. What does `val label = if total > 100 then "large" else "small"` show about Scala?

  1. if cannot return values
  2. val is mutable
  3. if is an expression that produces a value
  4. Strings must be declared with var
Show answer

Answer: if is an expression that produces a value

In Scala, if/else, match and blocks are expressions with results.

Lesson: Values, Types and Expressions

Control Flow, Collections and Functions

4. What does the compiler translate a for comprehension with yield into?

  1. A while loop
  2. Java bytecode directly with no method calls
  3. Calls to map, flatMap and withFilter
  4. Recursive functions only
Show answer

Answer: Calls to map, flatMap and withFilter

Generators and guards desugar into flatMap, map and withFilter, so any type with those methods works.

Lesson: Conditionals, Loops and for Comprehensions

5. What happens when you call `updated` on an immutable Map?

  1. The original map is changed
  2. A new map is returned and the original is unchanged
  3. An exception is thrown
  4. The map becomes mutable
Show answer

Answer: A new map is returned and the original is unchanged

Immutable collection operations return new collections, sharing structure where possible.

Lesson: Immutable Collections

6. What does a by-name parameter `action: => A` do?

  1. Delays evaluating the argument until it is used, possibly several times
  2. Evaluates the argument once before the call
  3. Makes the parameter optional
  4. Passes the argument by reference like C++
Show answer

Answer: Delays evaluating the argument until it is used, possibly several times

By-name arguments are evaluated each time they are referenced inside the method.

Lesson: Functions as Values

Classes, Traits and Data Modelling

7. What is a companion object?

  1. An object with the same name as a class in the same file, which can access its private members
  2. A subclass
  3. A copy of every instance
  4. A Java interface
Show answer

Answer: An object with the same name as a class in the same file, which can access its private members

Companions share privacy with their class and typically hold factories and constants.

Lesson: Classes, Objects and Companions

8. With `new Gateway with Logging with Validating`, which trait's charge runs first?

  1. Logging
  2. Gateway
  3. They run in parallel
  4. Validating
Show answer

Answer: Validating

Linearisation puts the rightmost trait first; its super call reaches Logging, then the class.

Lesson: Traits and Mixin Composition

9. What does making a hierarchy sealed (or using an enum) enable?

  1. Faster runtime dispatch only
  2. Mutable fields
  3. Compiler exhaustiveness checks in pattern matches, because all cases are known
  4. Multiple inheritance of classes
Show answer

Answer: Compiler exhaustiveness checks in pattern matches, because all cases are known

A closed set of cases lets the compiler warn when a match misses one.

Lesson: Case Classes, Enums and ADTs

Functional Programming in Scala

10. What happens when no case matches a value in a match expression?

  1. It returns null
  2. The first case is used
  3. A MatchError is thrown at run time
  4. The program fails to compile in every case
Show answer

Answer: A MatchError is thrown at run time

Non-exhaustive matches can fail at run time with MatchError; sealed types let the compiler warn first.

Lesson: Pattern Matching

11. When is Either[E, A] a better choice than Option[A]?

  1. When you do not care why something failed
  2. When you need to report why a computation failed
  3. When values can never be missing
  4. When working only with Java code
Show answer

Answer: When you need to report why a computation failed

Either carries an error value on the Left side, while None carries no reason.

Lesson: Option, Either and Try

12. What does the @tailrec annotation do?

  1. Makes the compiler verify the recursive call is in tail position, compiling it into a loop
  2. Makes any recursive function fast
  3. Runs the function in parallel
  4. Caches results
Show answer

Answer: Makes the compiler verify the recursive call is in tail position, compiling it into a loop

It guarantees tail-call optimisation or a compile error.

Lesson: Immutability, Recursion and Folds

The Type System and Contextual Abstractions

13. Why is Array[A] invariant in Scala?

  1. Because arrays are mutable: a covariant array would allow writing a Cat into an Array[Dog]
  2. Arrays cannot hold objects
  3. Because of performance
  4. It is covariant
Show answer

Answer: Because arrays are mutable: a covariant array would allow writing a Cat into an Array[Dog]

Mutable containers both produce and consume elements, so covariance would be unsafe.

Lesson: Generics, Variance and Bounds

14. What does a context bound such as [A: Show] mean?

  1. A must extend Show
  2. A is optional
  3. Show is a subclass of A
  4. The method needs a given Show[A] instance from the context
Show answer

Answer: The method needs a given Show[A] instance from the context

Context bounds are shorthand for a using parameter of type Show[A].

Lesson: Givens, Using Clauses and Type Classes

15. What is the runtime cost of an opaque type alias such as opaque type Paise = Long?

  1. A wrapper object per value
  2. A reflection lookup
  3. None: at run time it is the underlying Long
  4. A boxed Java object always
Show answer

Answer: None: at run time it is the underlying Long

Opaque types are distinct only at compile time and erase to the underlying type.

Lesson: Extension Methods, Opaque Types and Union Types

Concurrency and Effects

16. In a for comprehension over Futures, how do you make two independent calls run in parallel?

  1. Use two separate for loops
  2. Use Await.result inside the for
  3. Start both futures (assign them to vals) before the for comprehension
  4. It always runs in parallel
Show answer

Answer: Start both futures (assign them to vals) before the for comprehension

Futures start when created, so creating them first lets them run concurrently.

Lesson: Futures and Asynchronous Code

17. What is a key difference between Cats Effect IO and a standard Future?

  1. IO cannot run concurrently
  2. IO is a lazy description that runs only when executed and can be re-run, while a Future starts eagerly
  3. Future supports cancellation but IO does not
  4. There is no difference
Show answer

Answer: IO is a lazy description that runs only when executed and can be re-run, while a Future starts eagerly

Effects are lazy and referentially transparent; Futures start immediately and memoise their result.

Lesson: Effect Systems: Cats Effect and ZIO

18. How do actors avoid locks around their state?

  1. Each actor processes one message at a time and its state is private, changed only by its own message handling
  2. They use synchronized blocks
  3. They never have state
  4. They use global variables
Show answer

Answer: Each actor processes one message at a time and its state is private, changed only by its own message handling

Encapsulated state plus sequential message processing removes the need for locks.

Lesson: Actors with Apache Pekko and Akka

Building, Testing and Data Engineering

19. What does aggregate do in an sbt root project?

  1. Runs tasks such as compile and test across the listed modules
  2. Merges all source files into one module
  3. Creates a fat JAR
  4. Downloads Scala
Show answer

Answer: Runs tasks such as compile and test across the listed modules

Aggregation forwards tasks to the aggregated projects.

Lesson: Projects with sbt

20. What does property-based testing with ScalaCheck do?

  1. Tests only one hard-coded input
  2. Measures performance
  3. Formats code
  4. Generates many random inputs to check that a property always holds, shrinking failures to minimal examples
Show answer

Answer: Generates many random inputs to check that a property always holds, shrinking failures to minimal examples

ScalaCheck generates inputs and shrinks counterexamples.

Lesson: Testing with MUnit and ScalaTest

21. When do Spark transformations such as filter and groupBy actually execute?

  1. Immediately when called
  2. At compile time
  3. Only when an action such as show, count or write is called
  4. Never; Spark only stores plans
Show answer

Answer: Only when an action such as show, count or write is called

Spark builds a lazy plan and executes it when an action needs the result.

Lesson: Scala for Data: Apache Spark

Services, Interop, Idioms and Revision

22. What is a key benefit of Tapir?

  1. It is a database driver
  2. It replaces the JVM
  3. Endpoints are defined once as values and interpreted into servers, clients and OpenAPI docs
  4. It formats code
Show answer

Answer: Endpoints are defined once as values and interpreted into servers, clients and OpenAPI docs

Tapir separates endpoint descriptions from their interpreters.

Lesson: Building HTTP Services

23. How should you handle a Java method that may return null?

  1. Call methods on it directly
  2. Wrap it with Option(value) so null becomes None
  3. Catch NullPointerException everywhere
  4. Convert it to a String
Show answer

Answer: Wrap it with Option(value) so null becomes None

Option(x) converts null to None and anything else to Some(x).

Lesson: Java Interoperability

24. Why can calling .get on an Option be dangerous?

  1. It throws an exception when the Option is None
  2. It is slow
  3. It changes the Option
  4. It returns null
Show answer

Answer: It throws an exception when the Option is None

Option.get on None throws NoSuchElementException; use getOrElse, fold or pattern matching.

Lesson: Idiomatic Scala and Common Pitfalls

25. Which Scala 3 feature creates a distinct compile-time type with no runtime wrapper?

  1. case class
  2. trait
  3. lazy val
  4. opaque type
Show answer

Answer: opaque type

Opaque type aliases erase to their underlying type at run time.

Lesson: Revision and Interview Questions

← Back to the course