Scala type aliases (syntax, examples)

In Scala you can declare a type alias. Typically you do this to create a simple alias for a more complex type.

Using a type alias to simplify a complex type

For example, on this page I note a good example where someone on StackOverflow first defined a type alias named Row, and then created a second type alias named Matrix as a list of rows:

type Row = List[Int]
type Matrix = List[Row]    

The type Matrix is easier to read than this:

List[List[Int]]

This is similar to a Haskell example I remember seeing, where a Word was defined as a list of characters, a Sentence was defined as a list of words, and a Paragraph was defined as a list of sentences:

type Word = List[Char]
type Sentence = List[Word]
type Paragraph = List[Sentence]

Paragraph is certainly easier to remember than List[List[List[Char]]].

Creating a more meaningful name with a type alias

You can also create a type alias to create a more meaningful name for a type. For example, many people model money/currency using a BigDecimal, so a type alias like this makes sense:

type Money = BigDecimal

You can then use the type alias Money as a normal type in your Scala classes, objects, traits, and methods, like these examples:

def getPrice(): Money = 10.50
def doublePrice(m: Money): Money = 2.0 * m

Type alias rules

There are just a few rules to know about using type aliases in Scala. The main rule to know about a type alias is that it must be defined inside a class, object, or package object.

Another “rule” to know isn’t really a rule, but a way to think about a type alias: when you use a type alias to declare a type parameter, as with these methods:

def getPrice(): Money = 10.50
def doublePrice(m: Money): Money = 2.0 * m

the type Money is literally replaced by the compiler with its equivalent type, BigDecimal, so the compiled code becomes this:

def getPrice(): BigDecimal = 10.50
def doublePrice(m: BigDecimal): BigDecimal = 2.0 * m

Summary: Scala type aliases

I’ll write more about Scala type aliases when I can, but I hope this is enough information to get you started working with them.

 

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.