Parameterized Types

As we’ve seen, not only is extending a class concise in Scala, but it’s also streamlined to alleviate some common programming errors. Generic or parameterized types further help to create classes and functions that can work with multiple different types. The types can be specified at compile time instead of code writing time, making the code more extensible without losing type safety.

Since in Scala you can create stand-alone functions, you can create parameterized functions as well. Let’s create one:

def​ echo[T](input1: T, input2: T) =
println(s​"got $input1 (${input1.getClass}) $input2 (${input2.getClass})"​)

Rather than specifying the echo function’s parameter types to be some ...

Get Pragmatic Scala now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.