Generics
A type parameter is a name for a type that the caller chooses. One definition of Box[A] works for an Int, a String or a list, and the compiler checks every use with the type the caller supplied. The parameter is written in square brackets, after the name of the class or the method.
A class with a type parameter
Box[A] holds one value of type A, and its map returns a box of a new type B. The call site writes neither type: Box(41) is a Box[Int] because 41 is an Int:
boxes.scala
case class Box[A](value: A):
def map[B](f: A => B): Box[B] = Box(f(value))
@main def boxes(): Unit =
val numbers = Box(41).map(_ + 1)
val text = Box("scala").map(_.toUpperCase)
println(numbers)
println(text.value)
println(Box(1) == Box(1))
println(Box[List[Int]](List(1, 2)))
scala-cli run --server=false boxes.scala
Box(42)
SCALA
true
Box(List(1, 2))
The inference runs inside out: Box(41) fixes A to Int, so map takes an Int => B and fixes B from what the function returns. When inference needs help, the argument can be written out, as in Box[List[Int]](List(1, 2)). Two boxes of equal values are equal because the case class writes equals from the field, whatever the type of it.
A method with type parameters
A method declares its parameters before its parameter list. zip2[A, B] pairs two lists element by element, and repeat[A] returns a list of one value:
methods.scala
def zip2[A, B](as: List[A], bs: List[B]): List[(A, B)] =
as.zip(bs)
def repeat[A](value: A, times: Int): List[A] =
List.fill(times)(value)
def first[A](values: List[A]): Option[A] =
values.headOption
@main def generic_methods(): Unit =
println(zip2(List(1, 2), List("a", "b")))
println(repeat(7, 3))
println(repeat("x", 2))
println(zip2[Int, Char](List(1), List('a')))
println(first(List(1, 2, 3)))
println(first(List.empty[String]))
scala-cli run --server=false methods.scala
List((1,a), (2,b))
List(7, 7, 7)
List(x, x)
List((1,a))
Some(1)
None
first(List.empty[String]) is None and not a compile error: an empty list of strings is a value, and the result says so as an Option[String]. The explicit call zip2[Int, Char](...) is the same method with the two parameters written out, which a page shows once so the shape is visible; ordinary code lets inference fill them in.
Related
- Variance and bounds: what a type parameter may be, and how a container of a subtype relates to one of the supertype.
- Type classes: the pattern a type parameter with a given instance builds.
- Lists and vectors: the generic collections of the standard library.
- Java: generics with the same erasure, and the wildcards Scala replaces with variance.
Article author: Arthur Isaev