Trait Basics
A trait is a bundle of abilities a class can pick up, like a skill card that says 'can swim'. It can hold both promises and ready-made actions.
In this page:
Syntax
trait TraitName {
def abstractMethod(): ReturnType
def concreteMethod(): ReturnType = expression
}
class ClassName extends TraitName {
def abstractMethod(): ReturnType = expression
}
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Trying to instantiate a trait with
new Greetable, when it can only be created via a class or an anonymous subclass. - Forgetting to define the abstract member
name, so the class does not compile. - Using
extendsfor a second trait, when the first usesextendsand the others needwith.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: