How can you prevent a class from being subclassed in Scala?

Instruction: Explain the method to prevent a class in Scala from being extended by another class.

Context: This question is designed to assess the candidate's understanding of encapsulation and inheritance control in Scala, specifically using the 'final' keyword to prevent a class from being subclassed.

Updated

Mark the class final to prevent subclassing:

final class Counter(var value: Int)

@main def finalClassExample(): Unit = {
  val counter = new Counter(1)
  counter.value = 2
  assert(counter.value == 2)
}

A declaration such as class Derived extends Counter(0) fails to compile. This protects the class's implementation from being changed through subclass overrides. Marking an individual method final prevents overriding that method while leaving the rest of the class extensible. Final modifier

final does not make fields immutable or operations thread-safe: the example intentionally has a mutable field. A sealed class or trait instead restricts direct subclasses to the same source file and is useful for closed alternatives; it is not the same as prohibiting all subclasses. These modifiers express inheritance constraints. A compiler or JIT may optimize with that information, but the modifier alone does not establish a measured speedup.

Related Questions