Explain the differences between abstract class and trait, with a focus on instantiation and state.
Instruction: Discuss the differences in instantiation and state management between Scala's abstract classes and traits.
Updated
An abstract class and a trait can both declare abstract members, implement methods, and hold mutable or immutable fields. A class has one superclass but can mix in multiple traits. Neither declaration alone creates an object; a concrete named or anonymous subclass must satisfy the remaining abstract members.
This Scala 3 example demonstrates anonymous implementations and independent state:
abstract class Counter(val label: String) {
private var current = 0
def tick(): Unit = { current += 1 }
def count: Int = current
def describe: String
}
trait Named(val name: String) {
private var reads = 0
def readCount: Int = reads
def readName(): String = { reads += 1; name }
}
@main def classTraitExample(): Unit = {
val counter = new Counter("jobs") {
def describe: String = s"$label: $count"
}
val first = new Named("Ava") {}
val second = new Named("Bo") {}
counter.tick()
assert(counter.describe == "jobs: 1")
assert(first.readName() == "Ava")
assert(first.readCount == 1 && second.readCount == 0)
}
new Counter(...) { ... } creates an anonymous concrete subclass, not an instance of the abstract class without implementation. The same anonymous-implementation technique applies to a trait. Trait fields belong to each implementing object; they are not automatically shared singleton state. Both kinds of mutable state need synchronization if concurrently accessed. Classes, traits and composition
Scala 3 supports trait parameters as shown; Scala 2 traits did not accept those constructor parameters, but could still contain fields and initialization code. Constructor argument and inheritance rules still apply when combining parameterized traits. Trait parameter rules
Choose an abstract class when a single superclass with its construction contract fits the model; choose traits for composable capabilities. Avoid initialization code that reads abstract or overridable members before the subclass initializes them. Stateful mixins can make initialization order and ownership harder to understand, so composition through ordinary objects can be clearer than adding another inherited responsibility.