Trait Basics
In this page:
Trait Basics
A trait is similar to an interface but can also provide concrete method implementations and fields, not just abstract signatures. Traits cannot take constructor parameters (before Scala 3), unlike abstract classes. Traits are the primary way Scala shares reusable behavior across otherwise unrelated classes.
Note: Unlike a class, a trait cannot take constructor parameters in Scala 2 -- keep any needed configuration as abstract members instead.
Example: Trait Basics
trait Greetable {
def name: String
def greet(): Unit = {
println(s"Hello, I'm $name")
}
}
class Person(val name: String) extends Greetable
object Main extends App {
val p = new Person("Alice")
p.greet()
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: