What is the difference between abstract class and trait in Scala?
Answer
Both abstract classes and traits can have abstract and concrete members, but they differ in several ways. Constructor parameters: abstract classes can have constructor parameters: abstract class Animal(name: String); traits cannot (Scala 2), but Scala 3 traits can have parameters. Multiple inheritance: a class can extend only one abstract class but can mix in multiple traits. Java interoperability: abstract classes compile to Java abstract classes (easy for Java code to extend); traits with implementations compile to interfaces with default methods (Java 8+). Initialization order: class initialization is more predictable than trait initialization. When to use abstract class: when you need constructor parameters (Scala 2), when designing for Java inheritance, or when creating a primary base type with shared state. When to use trait: for mixins, type classes, and behavior composition across unrelated classes. Prefer traits for most abstractions — they are more flexible.
More Scala Questions
View all →- Intermediate What is the type class pattern in Scala?
- Intermediate What is Akka and what is the actor model?
- Intermediate What is Apache Spark and how does Scala relate to it?
- Intermediate What is Scala's approach to concurrency with Futures and Promises?
- Intermediate What are Scala's monads and how do they work?