Scala Tutorial - Learn How To Use Type Alias: Type Aliasing Versus Case Class

By Nadim Bahadoor | Last updated: July 25, 2017 at 14:19 pm

Overview

In this tutorial, we will learn how to define and use type aliasing to create shortcuts to other types or functions.

 

Type aliasing can be useful to help you provide more meaningful names which represent your business or domain objects without having to create unnecessary types.

 

Steps

1. How to define a case class to represent a Donut object

Let's start by using a case class which we learned from the tutorial on case classes to represent a domain object of type Donut.


println("Step 1: How to define a case class to represent a Donut object")
case class Donut(name: String, price: Double, productCode: Option[Long] = None)

 

2. How to create instances or objects for the Donut case class

Use the following syntax to create instances or objects of the Donut case class.


println("\nStep 2: How to create instances or objects for the Donut case class")
val vanillaDonut: Donut = Donut("Vanilla", 1.50)
val glazedDonut: Donut = Donut("Glazed", 2.0)
println(s"Vanilla Donut = $vanillaDonut")
println(s"Glazed Donut = $glazedDonut")

You should see the following output when you run your Scala application in IntelliJ:


Step 2: How to create instances or objects for the Donut case class
Vanilla Donut = Donut(Vanilla,1.5,None)
Glazed Donut = Donut(Glazed,2.0,None)

 

3. How to use type alias to name a Tuple2 pair into a domain type called CartItem

Instead of using a Tuple2 type to represent a Donut with its corresponding quantity being bought by a customer, you can make use of type aliasing to alias the Tuple2 type.

 

As shown below, we are aliasing the Tuple2 type and giving it a more meaningful name of CartItem which is essentially a pair of Donut item with the quantity being bought.



println("\nStep 3: How to use type alias to name a Tuple2 pair into a domain type called CartItem")
type CartItem[Donut, Int] = Tuple2[Donut, Int]

 

4. How to create instances of the aliased typed CartItem

To create instances of the aliased CartItem type from Step 3 above, you simply need to make use of the new keyword.


println("\nStep 4: How to create instances of the aliased typed CartItem")
val cartItem = new CartItem(vanillaDonut, 4)
println(s"cartItem = $cartItem")
println(s"cartItem first value = ${cartItem._1}")
println(s"cartItem second value = ${cartItem._2}")

You should see the following output when you run your Scala application in IntelliJ:


Step 4: How to create instances of the aliased typed CartItem
cartItem = (Donut(Vanilla,1.5,None),4)
cartItem first value = Donut(Vanilla,1.5,None)
cartItem second value = 4

5. How to use an aliased typed into a function parameter

With the type alias CartItem from Step 3, creating a function to calculate the total cost of donut items in a shopping cart is more clear.

 

As an example, the function calculateTotal below has a function parameter which is a Sequence of type CartItem, where aliased Tuple2 type named CartItem expects a Donut and quantity pair.


println("\nStep 5: How to use an aliased typed into a function parameter")
def calculateTotal(shoppingCartItems: Seq[CartItem[Donut, Int]]): Double = {
  // calculate the total cost
  shoppingCartItems.foreach { cartItem =>
    println(s"CartItem donut = ${cartItem._1}, quantity = ${cartItem._2}")
  }
  10 // some random total cost
}

 

6. How to use a case class instead of an aliased typed

If however you need to be even more precise about your shopping cart items, you might as well create another case class instead of using type aliasing of Tuple2.


println("\nStep 6: How to use a case class instead of an aliased typed")
case class ShoppingCartItem(donut: Donut, quantity: Int)

val shoppingItem: ShoppingCartItem = ShoppingCartItem(Donut("Glazed Donut", 2.50), 10)
println(s"shoppingItem donut = ${shoppingItem.donut}")
println(s"shoppingItem quantity = ${shoppingItem.quantity}")

You should see the following output when you run your Scala application in IntelliJ:


Step 6: How to use a case class instead of an aliased typed
shoppingItem donut = Donut(Glazed Donut,2.5,None)
shoppingItem quantity = 10

 

7. How to use case class from Step 6 to represent a Sequence of Donut items in a shopping cart

Using the ShoppingCartItem case class from Step 6 is even more succinct that ShoppingCartItem holds a donut object and the quantity being bought.


println("\nStep 7: How to use case class from Step 6 to represent a Sequence of Donut items in a shopping cart")
def calculateTotal2(shoppingCartItems: Seq[ShoppingCartItem]): Double = {
 // calculate the total cost
 shoppingCartItems.foreach { shoppingCartItem =>
   println(s"ShoppingCartItem donut = ${shoppingCartItem.donut}, quantity = ${shoppingCartItem.quantity}")
 }
 10 // some random total cost
}

This concludes our tutorial on Learn How To Use Type Alias: Type Aliasing Versus Case Class and I hope you've found it useful!

 

Stay in touch via Facebook and Twitter for upcoming tutorials!

 

Don't forget to like and share this page :)

Summary

In this tutorial, we went over the following:

  • How to define a case class to represent a Donut object
  • How to create instances or objects for the Donut case class
  • How to use type alias to name a Tuple2 pair into a domain type called CartItem
  • How to create instances of the aliased typed CartItem
  • How to use an aliased typed into a function parameter
  • How to use a case class instead of an aliased typed
  • How to use case class from Step 6 to represent a Sequence of Donut items in a shopping cart

Tip

  • Use type aliasing when it helps make your code more clear regarding the domain objects you are dealing with.

Source Code

The source code is available on the allaboutscala GitHub repository.

 

What's Next

In the next tutorial, I will show you how to use an Implicit Class in Scala.

Nadim Bahadoor on FacebookNadim Bahadoor on GithubNadim Bahadoor on LinkedinNadim Bahadoor on Twitter
Nadim Bahadoor
Senior Software Developer | Nephila Capital
Founder of allaboutscala.com. I have over 10 years of experience in building large scale real-time trading systems in the financial industry. Passionate about Distributed Systems, Scala, Big Data and Functional Programming. Stay in touch for upcoming tutorials!
Other allaboutscala.com tutorials you may like:

Share this article on