Chapter 15. Scala’s Type System, Part II

This chapter continues the survey of the type system that we started in the previous chapter. The type features discussed here are the ones you’ll encounter eventually, but you don’t need to understand them right away if you’re new to Scala. As you work on Scala projects and use third-party libraries, if you encounter a type system concept that you haven’t seen before, you’ll probably find it covered here. (For more depth than we can cover here, see The Scala Language Specification.) Still, I recommend you skim the chapter. For example, you’ll see a few examples of path-dependent types in more advanced examples later in the book, although you won’t need a “deep” understanding of them.

Path-Dependent Types

Scala, like Java before it, lets you nest types. You can access nested types using a path expression.

Consider the following example:

// src/main/scala/progscala2/typesystem/typepaths/type-path.scalaX
package progscala2.typesystem.typepaths

class Service {                                                      1
  class Logger {
    def log(message: String): Unit = println(s"log: $message")       2
  val logger: Logger = new Logger

val s1 = new Service
val s2 = new Service { override val logger = s1.logger }     // ERROR!  

Define a class Service with a nested class Logger.

Use println for simplicitly. ...

Get Programming Scala, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.