19.1. Creating Classes That Use Generic Types

Problem

You want to create a class (and associated methods) that uses a generic type.

Solution

As a library writer, creating a class (and methods) that takes a generic type is similar to Java. For instance, if Scala didn’t have a linked list class and you wanted to write your own, you could write the basic functionality like this:

class LinkedList[A] {

  private class Node[A] (elem: A) {
    var next: Node[A] = _
    override def toString = elem.toString
  }

  private var head: Node[A] = _

  def add(elem: A) {
    val n = new Node(elem)
    n.next = head
    head = n
  }

  private def printNodes(n: Node[A]) {
    if (n != null) {
      println(n)
      printNodes(n.next)
    }
  }

  def printAll() { printNodes(head) }

}

Notice how the generic type A is sprinkled throughout the class definition. This is similar to Java, but Scala uses [A] everywhere, instead of <T> as Java does. (More on the characters A versus T shortly.)

To create a list of integers with this class, first create an instance of it, declaring its type as Int:

val ints = new LinkedList[Int]()

Then populate it with Int values:

ints.add(1)
ints.add(2)

Because the class uses a generic type, you can also create a LinkedList of String:

val strings = new LinkedList[String]()
strings.add("Nacho")
strings.add("Libre")
strings.printAll()

Or any other type you want to use:

val doubles = new LinkedList[Double]()
val frogs = new LinkedList[Frog]()

At this basic level, creating a generic class in Scala is just like creating a generic class in Java, with ...

Get Scala Cookbook 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.