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.

In the meantime, 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*) = List(xs: _*)
 
    type Matrix = List[Row]
    def Matrix(xs: Row*) = 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 find that I use type aliases more often 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.

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.