Chapter 6. The Type System

 

In this chapter

  • Structural types
  • Using type constraints
  • Type parameters and higher-kinded types
  • Existential types

The type system is an important component of the Scala language. It enables lots of rich optimizations and constraints to be used during compilation, which helps runtime speed and prevents programming errors. The type system allows us to create all sorts of interesting walls around ourselves, known as types. These walls help prevent us from accidentally writing improper code. This is done through the compiler tracking information about variables, methods, and classes. The more you know about Scala’s type system, the more information you can give the compiler, and the type walls become less restrictive while still providing the same protection.

When using a type system, it’s best to think of it as an overprotective father. It will constantly warn you of problems or prevent you from doing things altogether. The better you communicate with the type system, the less restrictive it becomes. But if you attempt to do something deemed inappropriate, the compiler will warn you. The compiler can be a great means of detecting errors if you give it enough information.

6.1. Types

6.2. Type constraints

6.3. Type parameters and higher-kinded types

6.4. Variance

6.5. Existential types

6.6. Summary