🔴 Scala Beginner

What are traits in Scala?

Answer

Traits in Scala are similar to Java's interfaces but more powerful — they can have concrete method implementations, fields, and abstract members. Define a trait: trait Greeting { def greet(name: String): String = s"Hello, $name" }. A class can mix in multiple traits: class Person extends Human with Greeting with Serializable. Unlike Java interfaces (before Java 8), Scala traits could always have implementations. Traits resolve the diamond problem (multiple inheritance conflict) using linearization: the MRO (Method Resolution Order) is determined by the order traits are mixed in, right to left. Traits can also be used as mix-ins: new Animal with Logging. The combination of abstract and concrete members in traits enables the template method pattern cleanly. Traits are foundational to Scala's type system and component model.