Traits

trait Iterator[A] {
  def hasNext: Boolean
  def next(): A
}
trait Greeter {
  def greet(name: String): Unit
}
trait Greeter {
  def greet(name: String): Unit =
    println("Hello, " + name + "!")
}
class DefaultGreeter extends Greeter

class CustomizableGreeter(prefix: String, postfix: String) extends Greeter {
  override def greet(name: String): Unit = {
    println(prefix + name + postfix)
  }
}

val greeter = new DefaultGreeter()
greeter.greet("Scala developer") // Hello, Scala developer!

val customGreeter = new CustomizableGreeter("How are you, ", "?")
customGreeter.greet("Scala developer") // How are you, Scala developer?

Is abstract data types containing certain fields and methods.

It is used to share interfaces and fields between classes. Classes and objects can extend traits but traits cannot be instantiated and therefore have no parameters.

Traits:

Traits — Structure map

Clickable & Draggable!

Traits — Related pages: