Understanding what 'type' keyword does in Scala

Core_Dumped picture Core_Dumped · Oct 21, 2013 · Viewed 68.8k times · Source

I am new to Scala and I could not really find a lot about the type keyword. I am trying to understand what the following expression may mean:

type FunctorType = (LocalDate, HolidayCalendar, Int, Boolean) => LocalDate

FunctorType is some kind of an alias, but what does it signify?

Answer

Marius Danila picture Marius Danila · Oct 21, 2013

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