Introduction

As you can tell from one look at the Scaladoc for the collections classes, Scala has a powerful type system. However, unless you’re the creator of a library, you can go a long way in Scala without having to go too far down into the depths of Scala types. But once you start creating collections-style APIs for other users, you will need to learn them.

This chapter provides recipes for the most common problems you’ll encounter, but when you need to go deeper, I highly recommend the book, Programming in Scala, by Odersky, Spoon, and Venners. (Martin Odersky is the creator of the Scala programming language, and I think of that book as “the reference” for Scala.)

Scala’s type system uses a collection of symbols to express different generic type concepts, including variance, bounds, and constraints. The most common of these symbols are summarized in the next sections.

Variance

Type variance is a generic type concept, and defines the rules by which parameterized types can be passed into methods. The type variance symbols are briefly summarized in Table 19-1.

Table 19-1. Descriptions of type variance symbols

Symbols

Name

Description

Array[T]

Invariant

Used when elements in the container are mutable.

Example: Can only pass Array[String] to a method expecting Array[String].

Seq[+A]

Covariant

Used when elements in the container are immutable. This makes the container more flexible.

Example: Can pass a Seq[String] to a method expected Seq[Any].

Foo[-A]

Function1[-A, +B]

Contravariant

Contravariance ...

Get Scala Cookbook 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.