What is a trait in Scala, and how does it differ from an abstract class?
Instruction: Define traits in Scala and compare them with abstract classes, highlighting key differences.
Updated
A trait defines a reusable contract and may contain both abstract and concrete members. An abstract class can also contain both. Neither can be instantiated directly as a concrete value without a concrete subclass; an anonymous subclass can supply required implementations.
A Scala class extends at most one class and can mix in multiple traits. This supports composing capabilities across otherwise unrelated class hierarchies. Traits can contain state as well as methods; they are not limited to stateless interfaces.
In Scala 3, traits can also take parameters:
trait Named(val name: String) {
def label: String = s"name=$name"
}
trait Identified {
def id: Int
}
abstract class Entity(val createdBy: String) {
def describe: String
}
final class User(val id: Int, name: String)
extends Entity("example") with Named(name) with Identified {
def describe: String = s"$id:$label"
}
@main def traitExample(): Unit = {
assert(new User(7, "Ava").describe == "7:name=Ava")
}
Scala 2 traits do not take constructor parameters in this form. Scala 3 trait parameter passing has inheritance rules, so it is not identical in every respect to superclass construction. Trait parameters
Use a trait for a capability or reusable mixin; use an abstract class when a shared class base and its constructor are central to the model. Both approaches require care with initialization order, especially when a constructor invokes an overridable member. Multiple concrete implementations can also require an explicit override to resolve a conflict. Choose the smallest understandable hierarchy rather than assuming one construct is universally more flexible.