Chapter 9Type System

This chapter begins with an overview of type systems in general and highlights the main difference between static and dynamic typing. Then it shows the main features of the powerful Scala type system. The different types of polymorphisms are examined showing how Scala excels compared to Java thanks to ad hoc polymorphism through type classes. Type bounds is another powerful concept shown in this chapter. Roughly speaking, a bound lets you restrict the set of possible types that can be used in your data structures.

Due to the presence of both subtype and parametric polymorphism, you are forced to face, sooner or later, the concept of variance. You'll find out how to define your data structures as covariant, contravariant or invariant, and use bounds to satisfy the compiler complaints. You'll also meet other Scala type system niceties such as: self-type annotations, self-recursive types and abstract type members. Finally, you'll see how Scala let you simulate dynamic typing that allows you to deal with some situations where static typing is not a feasible solution.

Take into account that Scala's type system is a big subject that cannot be fully covered in a chapter or two. You can easily write an entire book about it, and the shapeless project (https://github.com/milessabin/shapeless ...

Get Professional Scala now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.