Scala Type Parameters
A type parameter is a placeholder for a type in a class or a method. The caller fills in the placeholder with a real type when the code is used.
One box class holds any type
Box takes a type parameter named T. An integer box and a string box use the same class.
class Box[T](val value: T)
@main def main(): Unit =
val intBox = Box(42)
val textBox = Box("hi")
println(intBox.value)
println(textBox.value)A generic method works for any type
identity returns whatever it receives. It works for an integer and for a string.
def identity[T](x: T): T = x
@main def main(): Unit =
println(identity(42))
println(identity("hi"))A generic method can return a pair
pair takes two values of the same type. It returns them together as one pair.
def pair[T](a: T, b: T): (T, T) = (a, b)
@main def main(): Unit =
println(pair(1, 2))
println(pair("a", "b"))Example
class Box[T](val value: T)
def pair[T](a: T, b: T): (T, T) = (a, b)
@main def main(): Unit =
val numberBox = Box(7)
val wordBox = Box("seven")
println(numberBox.value)
println(wordBox.value)
println(pair(numberBox.value, 8))
println(pair(wordBox.value, "eight"))Key points
- Placeholder: the letter T stands for a type that is not chosen yet.
- One class many types: Box[Int] and Box[String] are two versions of the same class.
- Inference: the compiler often works out the real type from the values given.
- Reuse: one generic definition replaces many near-identical definitions.
- Naming: a single letter such as T is the usual name for a type parameter.
In this example, numberBox is a box of integers and wordBox is a box of strings, both from the same Box class, and pair groups two values of the same type in each call.
Note
a type parameter is not a value, so it cannot be printed or added.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does Box[String] mean?