Chapter 6: Parameterized Types

In Scala, there are two major ways to design your generic or reusable code. Those are Parameterized Types and Abstract Types. Both of them have their own pros and cons. In this chapter, we will try to explore parameterized types. Let's start with layman definition, Parameterized types are those types which are declared by types or classes via type constructor( [ ] ).

From chapter 2nd, we have an idea about types and classes Now the question is, what is type constructor? A type constructor is used to constructing a new type from passed type parameter. Take an example from the below code:

trait Java
trait Scala

class Book[T] { … }

new Book[Java] // creates new type Book of Java
new Book[Scala] // creates a new type Book of Scala

In the above example, we are creating two new types which are Java and Scala , after that create another parameterized type which is called a Book[T]. Why Book is called the Parameterized type? Because the book contains a type constructor as of [T], while we are passing Java as a type parameter, it creates a new type which is called Book[Java] (Book of Java). This concept is similar to construct a new object via class constructor like below:

class Book(`type`: String)
new Book(“Java”) // creates a new object Book which contains Java
new Book(“Scala”)  // creates a new object Book which contains Scala. 

Via type constructor, we can create new types as per our requirement. Always remember, creating a new type means Book[Java] (Book of Java) type is always different from Book[Scala] (Book of Scala) type similar to new Book(“Java”) object is different from new Book(“Scala”) object. Type constructor contains more than one parameters like:

trait Flow[In, Out]
trait Http[Request, Response]

The name of the type parameter depends on the type you are creating, like in the above code, we are creating two types. Flow which contains In and Out parameters. We can use any character here, but for the conventions perspective, we need to use name, which defines the purpose of the type parameter. The basic convention of type parameters which is followed in Java as well, for declaring types, prefer to use a single character in a capital letter as we declared in Book class.

We can define type constructor with traits, classes, and method. In methods type constructor not creating a new type, but it helps to define generic type parameters to method arguments like below:

def add[T](a: T, b: T): T

add[Int](3, 4)
add[String](“Harmeet”, “Singh”)

Because of type constructor in the add method, we can use the same method for various types as per our requirements. The implementation of these methods could be the same or different, that we will explore in chapter 8th using type classes and ad-hoc polymorphism.

Last updated