Scala Tutorial - Learn How To Create Function Using The Val Keyword Instead Of Def

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

Overview

In this tutorial, we will learn how to create value functions which are defined using the val keyword as opposed to using the def keyword.

 

In addition, we will show how to pass through the val function to a Higher Order Function.

Steps

1. How to define a higher order function which takes another function as parameter

Let's review the function totalCostWithDiscountFunctionParameter() which we used in the Higher Order Function tutorial.


println("\nStep 1: How to define a higher order function which takes another function as parameter")
def totalCostWithDiscountFunctionParameter(donutType: String)(quantity: Int)(f: Double => Double): Double = {
  println(s"Calculating total cost for $quantity $donutType")
  val totalCost = 2.50 * quantity
  f(totalCost)
}

NOTE:

  • The function has a by-name parameter which is expected to be a function that has a parameter of type Double and will also return a type of Double.
  • The by-name parameter function will apply some discount to the totalCost value.

2. How to define and pass a def function to a higher order function

Let's also review how we defined a discount function using the def keyword and passed it to the Higher Order Function totalCostWithDiscountFunctionParameter()


println("\nStep 2: How to define and pass a def function to a higher order function")
def applyDiscount(totalCost: Double): Double = {
  val discount = 2 // assume you fetch discount from database
  totalCost - discount
}
println(s"Total cost of 5 Glazed Donuts with discount def function = ${totalCostWithDiscountFunctionParameter("Glazed Donut")(5)(applyDiscount(_))}")

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


Step 2: How to define and pass a def function to a higher order function
Calculating total cost for 5 Glazed Donut
Total cost of 5 Glazed Donuts with discount def function = 10.5

 

3. How to define and pass a val function to a higher order function

If you've also reviewed the Scala Features Tutorial, you should already be familiar with the fact that functions are first class citizens in Scala.

 

As a result, Scala allows you to define value function using the val keyword as shown below:


println("\nStep 3: How to define and pass a val function to a higher order function")
val applyDiscountValueFunction = (totalCost: Double) => {
  val discount = 2 // assume you fetch discount from database
  totalCost - discount
}
println(s"Total cost of 5 Glazed Donuts with discount val function = ${totalCostWithDiscountFunctionParameter("Glazed Donut")(5)(applyDiscountValueFunction)}")

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


Step 3: How to define and pass a val function to a higher order function
Calculating total cost for 5 Glazed Donut
Total cost of 5 Glazed Donuts with discount val function = 10.5

NOTE:

  • The syntax for defining value function is slightly different to functions defined with def keyword.
  • In val applyDiscountValueFunction = (totalCost: Double) => { ... } we did not specify the return type of the function and are making use of Scala Type Inference.
  • If you want to add the return type, the syntax for the value function would look as follows: val applyDiscountValueFunction: Double => Double = totalCost => { ... }
  • When passing the value function to the Higher Order Function, you no longer need to explicitly make use of the wildcard operator _

This concludes our tutorial on Learn How To Create Function Using The Val Keyword Instead Of Def 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 higher order function which takes another function as parameter
  • How to define and pass a def function to a higher order function
  • How to define and pass a val function to a higher order function

Tip

  • You can learn more about call-by-name function parameters from the Scala specification.
  • val functions are instances of FunctionN classes and if you look at the Scala documentation for say Function1 class, you will notice that val function will inherit other methods such as andThen or compose which allow for function composition.

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 val function as part of function composition.

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