Anonymous Classes and Single Abstract Method Types

(, en)

Scala suppports, similar to Java, a way to define anonymous classes. Let’s assume we have an interface

// src/main/scala/AnonymousClasses.scala
trait Greetings {
  def greet(name: String): Unit
}

then a anonymous class implementing this interface looks like

// src/main/scala/AnonymousClasses.scala
val greeter: Greetings = new Greetings {
  override def greet(name: String): Unit = println(s"Hallo $name")
}

The cool thing about Scala is that you can reduce the verboseness by using the Single Abstract Method type:

// src/main/scala/AnonymousClasses.scala
val greeterSingleAbstractMethod: Greetings = (name: String) => println(s"Hallo $name")

See also