Scala Tutorial - Learn How To Create Polymorphic Function With Generic Return Type

By Nadim Bahadoor | Last updated: July 25, 2017 at 13:46 pm

Overview

In this tutorial, we will learn how to create polymorphic functions which will allow you to specify the types of the parameters as well as the return type of the function.

 

This tutorial is a continuation of the previous tutorial on Typed Functions where you learned how to create functions which have typed parameters.

Steps

1. Review how to define a generic typed function which will specify the type of its parameter

Let's first review what we've learned from the previous tutorial on Typed Functions. Typed functions allow you to define functions where you can specify the type of its parameters.

 

In the previous tutorial, we defined an applyDiscount() function which has a generic type parameter named discount.


println("\nStep 1: Review how to define a generic typed function which will specify the type of its parameter")
def applyDiscount[T](discount: T) {
  discount match {
    case d: String =>
      println(s"Lookup percentage discount in database for $d")

    case d: Double =>
      println(s"$d discount will be applied")

    case _ =>
      println("Unsupported discount type")
  }
}

 

2. Review how to call a function which has typed parameters

To call the typed function applyDiscount() from Step 1, you have to specify the type of the discount parameter as follows:


println("\nStep 2: Review how to call a function which has typed parameters")
applyDiscount[String]("COUPON_123")
applyDiscount[Double](10)

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


Step 2: Review how to call a function which has typed parameters
Lookup percentage discount in database for COUPON_123
10.0 discount will be applied

NOTE:

  • Sure you can rely on Scala's type inference to infer the type of your function parameter.
  • But in general it's a good practice to explicitly specify your parameter types.

3. How to define a polymorphic typed function which also has a generic return type

With the applyDiscount() function from Step 1 in mind, let us define another function which will be polymorphic in nature. We will name the function applyDiscountWithReturnType() and it will take a generic type T for its discount parameter. But it will also return a Sequence of the type T.


println("\nStep 3: How to define a generic typed function which also has a generic return type")
def applyDiscountWithReturnType[T](discount: T): Seq[T] = {
  discount match {
    case d: String =>
      println(s"Lookup percentage discount in database for $d")
      Seq[T](discount)

  case d: Double =>
      println(s"$d discount will be applied")
      Seq[T](discount)

  case d @ _ =>
      println("Unsupported discount type")
      Seq[T](discount)
  }
}

NOTE:

  • For simplicity, we are returning a new Sequence of type T for each of the cases within the pattern match.

4. How to call a generic polymorphic function which also has a generic return type

Let us call the polymorphic applyDiscountWithReturnType() function from Step 3 with different types namely String, Double and Char.


println("\nStep 4: How to call a generic typed function which also has a generic return type")
println(s"Result of applyDiscountWithReturnType with String parameter = ${applyDiscountWithReturnType[String]("COUPON_123")}")

println()
println(s"Result of applyDiscountWithReturnType with Double parameter = ${applyDiscountWithReturnType[Double](10.5)}")

println()
println(s"Result of applyDiscountWithReturnType with Char parameter = ${applyDiscountWithReturnType[Char]('U')}")

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


Step 4: How to call a generic typed function which also has a generic return type
Lookup percentage discount in database for COUPON_123
Result of applyDiscountWithReturnType with String parameter = List(COUPON_123)

10.5 discount will be applied
Result of applyDiscountWithReturnType with Double parameter = List(10.5)

Unsupported discount type
Result of applyDiscountWithReturnType with Char parameter = List(U)

NOTE:

  • For each of the specified types used when calling the polymorphic function applyDiscountWithReturnType(), the function also returns the Sequence of the same type.

This concludes our tutorial on Learn How To Create Polymorphic Function With Generic Return Type 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:

  • Reviewed how to define a generic typed function which will specify the type of its parameter
  • Reviewed how to call a function which has typed parameters
  • How to define a polymorphic typed function which also has a generic return type
  • How to call a generic polymorphic function which also has a generic return type

Tip

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 define functions which take variable arguments.

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