Extension Methods in Depth
Extension methods in depth are extensions that work for many types at once. An extension method is a method added to an existing type from outside that type.
One extension works for a list of any element type
The firstTwo extension takes a type parameter A. It returns the first two items of a list of A.
extension [A](xs: List[A])
def firstTwo: List[A] = xs.take(2)
@main def main(): Unit =
println(List(1, 2, 3).firstTwo)
println(List("a", "b", "c").firstTwo)An extension can pick an item by position
The second extension also uses a type parameter. It returns the item at index 1.
extension [A](xs: List[A])
def second: A = xs(1)
@main def main(): Unit =
println(List(10, 20, 30).second)A type parameter also works on a single value
This extension takes a type parameter for one value. It pairs that value with another value of the same type.
extension [A](x: A)
def pairWith(y: A): (A, A) = (x, y)
@main def main(): Unit =
println(1.pairWith(2))
println("x".pairWith("y"))Example
extension [A](xs: List[A])
def firstTwo: List[A] = xs.take(2)
extension [A](x: A)
def pairWith(y: A): (A, A) = (x, y)
@main def main(): Unit =
println(List(5, 6, 7, 8).firstTwo)
println(List("p", "q", "r").firstTwo)
println(3.pairWith(4))Key points
- Type parameter: a placeholder for a type, written in square brackets before the receiver.
- Generic type: a type that takes a type placeholder, such as List of A.
- Generic extension: one extension written with a type parameter works for every choice of that parameter.
- Receiver: the value the extension method is called on.
- Use a type parameter on the extension when the method must work for lists of numbers and lists of words alike.
In this example, the first extension returns the first two items of a list. The second extension pairs one value with another of the same type. The program prints the first two numbers, the first two words, and a pair of numbers.
Note
the extension method sees the element type only as A, so it cannot assume numbers or words.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does extension [A](xs: List[A]) let firstTwo do?