Understanding what ‘type’ keyword does in Scala

Actually the type keyword in Scala can do much more than just aliasing a complicated type to a shorter name. It introduces type members.

As you know, a class can have field members and method members. Well, Scala also allows a class to have type members.

In your particular case type is, indeed, introducing an alias that allows you to write more concise code. The type system just replaces the alias with the actual type when type-checking is performed.

But you can also have something like this

trait Base {
  type T

  def method: T

class Implementation extends Base {
  type T = Int

  def method: T = 42

Like any other member of a class, type members can also be abstract (you just don’t specify what their value actually is) and can be overridden in implementations.

Type members can be viewed as dual of generics since much of the things you can implement with generics can be translated into abstract type members.

So yes, they can be used for aliasing, but don’t limit them to just this, since they are a powerful feature of Scala’s type system.

Please see this excellent answer for more details:

Scala: Abstract types vs generics

Leave a Comment