Abstract types

Another way to parameterize classes is by using abstract types. Generics have their counterparts in other languages such as Java. Unlike them, however, abstract types do not exist in Java. Let's see how our preceding Container example will translate into one with abstract types, rather than generics:

trait ContainerAT {  type T  val data: T    def compare(other: T) = data.equals(other)}

We will use the trait in a class, as follows:

class StringContainer(val data: String) extends ContainerAT {  override type T = String}

After we've done this, we can have the same example as before:

object AbstractTypesExamples {  def main(args: Array[String]): Unit = {    val stringContainer = new StringContainer("some text") System.out.println(s"Comparing ...

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.