Chapter 16. Scala’s Type System, Part I

By now, you know quite a lot about Scala’s type system. This chapter and the next fill in some details and introduce more advanced constructs.

Scala is a statically typed language. Its sophisticated type system combines FP and OOP. The type system tries to be logically comprehensive, complete, and consistent.

Ideally, a type system is expressive enough to prevent your applications from ever inhabiting an invalid state. It lets you enforce these constraints at compile time, so runtime failures never occur. In practice, we’re far from that goal, but Scala’s type system pushes the boundaries of what’s possible.

However, Scala’s type system can be intimidating. When people claim that Scala is complex, they usually have the type system in mind.

Fortunately, type inference hides many of the details. Mastery of the more arcane aspects of the type system is not required to use Scala effectively, although you’ll eventually need to be familiar with most constructs.

Now let’s begin by revisiting familiar ground, parameterized types.

Parameterized Types

In “Parameterized Types: Variance Under Inheritance”, we explored variance under subtyping. Recapping, a declaration like Seq[+A] means that Seq is parameterized by a single type, represented by A. The + is a variance annotation, indicating that Seq is covariant in the type parameter. This means that Seq[String] is considered a subtype of Seq[AnyRef] because String is a subtype of AnyRef.

Similarly, ...

Get Programming Scala, 3rd Edition 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.