Scala Generic Methods
A generic method is a method that declares its own type parameters. The type parameters belong to the method, not to the class around it.
One method returns the first item of any list
firstItem works for integers and for strings. Each call returns the first item.
def firstItem[T](xs: List[T]): T = xs.head
@main def main(): Unit =
println(firstItem(List(1, 2, 3)))
println(firstItem(List("a", "b")))One method can pair two different types
pair takes two type parameters, A and B. Each call pairs two values of different types.
def pair[A, B](a: A, b: B): (A, B) = (a, b)
@main def main(): Unit =
println(pair(1, "one"))
println(pair("two", 2))A caller can pin the type with brackets
The first call pins the type to Int with brackets. The second call pins the type to String the same way.
def wrap[T](x: T): List[T] = List(x)
@main def main(): Unit =
println(wrap[Int](7))
println(wrap[String]("seven"))Example
def firstItem[T](xs: List[T]): T = xs.head
def pair[A, B](a: A, b: B): (A, B) = (a, b)
def wrap[T](x: T): List[T] = List(x)
@main def main(): Unit =
println(firstItem(List(10, 20)))
println(pair(3, "three"))
println(wrap("done"))Key points
- Method scope: the type parameter is declared on the method itself, as in def first[T].
- Inference: the compiler usually works out T from the arguments at the call.
- Two parameters: a method can declare two type parameters, such as A and B, for two different types.
- Explicit types: a caller can pin the type with brackets, as in wrap[Int](7).
- Reuse: one generic method replaces a separate method for each type.
In this example, firstItem returns the first number of a list, pair groups a number with a word, and wrap puts a word into a list.
Note
a generic method needs no generic class around it, so it can live in a plain program.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
Where does a generic method declare its type parameter?