Scala type examples (type aliases and type members)

At some point I want to write more about Scala type aliases and type members, but for today I just want to put a little reminder here for myself.

Until I take the time to write more, here are two images from stackoverflow that provide Scala type examples.

Using Scala type aliases

This first image is from this link, and discusses the difference between a type and a value:

Scala type example - Trying to use type alias as a value

Here’s the source code to go along with that image, with a few println statements at the end:

object TypeAliases1 extends App {

    type Row = List[Int]
    def Row(xs: Int*): Row = List(xs: _*)
 
    type Matrix = List[Row]
    def Matrix(xs: Row*): Matrix = List(xs: _*)
 
    val m = Matrix(Row(1,2,3),
                   Row(1,2,3),
                   Row(1,2,3))

    println(m)
    println(m.getClass)

}

As programs get more complicated, I sometimes use type aliases to help simplify them. For instance, I just created this type alias in a Scala object:

type DataTypeMap = Map[String, DataTypeAsJson]

and then ended up using it later in several places, like this:

def getAllDataTypesAsMap(jsonString: String): DataTypeMap = {

For my brain, it makes it easier to look at the getAllDataTypesAsMap method and reason about what it returns.

As shown in the image above, a problem comes along when you try to use a type alias as a value (as a class or object), and that image and source code show the solution to that problem.

Scala type members

This next image is from this SO link, and shows an example of creating a Scala type member:

Scala type members

Summary

Again, I hope to come back here and share some more Scala type examples for both type aliases and type members, but until then, I hope this information is helpful.