Scala Language Traits Trait Basics

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

This is the most basic version of a trait in Scala.

trait Identifiable {
  def getIdentifier: String
  def printIndentification(): Unit = println(getIdentifier)
}

case class Puppy(id: String, name: String) extends Identifiable {
  def getIdentifier: String = s"$name has id $id"
}

Since no super class is declared for trait Identifiable, by default it extends from AnyRef class. Because no definition for getIdentifier is provided in Identifiable, the Puppy class must implement it. However, Puppy inherits the implementation of printIdentification from Identifiable.

In the REPL:

val p = new Puppy("K9", "Rex")
p.getIdentifier  // res0: String = Rex has id K9
p.printIndentification()  // Rex has id K9


Got any Scala Language Question?