← Back to Scala Course | Chapter 8: Inheritance & Traits | Lesson 4 of 7

Trait Basics

In this page:

  1. Trait Basics

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

markup
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()
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.