Chapter 17. Scala’s Type System, Part II

This chapter continues the type system survey that we started in the previous chapter, covering more advanced constructs. You can skip this chapter until you need to understand the concepts discussed here.

Let’s begin with match types and the broad subject of dependent typing.

Match Types

Scala 3 extends pattern matching to work at the type level for match types. Let’s look at an example adapted from the Scala documentation. The following match type definition returns a type that is the type parameter of another type with one type parameter. For example, for Seq[Int] it will return Int:

// src/script/scala/progscala3/typesystem/matchtypes/MatchTypes.scala

type Elem[X] = X match                                          1
  case String => Char                                           2
  case IterableOnce[t] => t                                     3
  case Array[t] => t
  case ? => X                                                   4
1

Define a match type. It uses a match expression with case clauses to resolve the type.

Special case handling of Strings, which are actually Array[Char].

scala.collection.IterableOnce is ...

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.