Scala Function Tutorial – Types of Functions in Scala

1. Scala Function – Objective

In this tutorial, we will discuss some Scala Functions. Moreover, we will study how to define and declare functions in Scala. Along with this, we will learn how to call your own Scala function. At last, we will cover different types of Scala Functions.

So, let’s start the Scala Function Tutorial.

Scala Functions

Scala Functions

2. What is Scala Function?

When we want to execute a group of statements to perform a task a hundred times, we don’t type them a hundred times. We group them into a function, put a call to that function inside a loop, and make that loop run a hundred times. Well, dividing our code into functions also makes for modularity – it makes it easier to debug and modify the code. We can do this division according to the tasks we carry out in our code.

Scala is rich with built-in functions, and it also lets us create our own. Here, Scala function is first-class value.

Scala also has methods, but these differ only slightly from Scala function. A method belongs to a class; it has a name, a signature, [optionally, ] some annotations, and some bytecode. A function is a complete object that we can store in a variable. Then, a method is a function that is a member of some object. You can also learn Scala Variable and Other Scala tutorials from our blog long with Scala Functions.

3. Declaring a Function in Scala

To create a Scala function, we use the keyword ‘def’.

a. Syntax

Here’s the syntax you’ll want to follow:

def functionName(parameters:typeofparameters):returntypeoffunction={
//statements to be executed
}

Now here, while you must mention the types of parameters, the type of Scala function is optional. What else is optional is the ‘=’ operator. Let’s see examples for each kind of declaration.

b. Without = | Without Parameters

You can consider this to be the simplest kind of Scala function declaration.

scala> def sayhello(){
    | println("Hello")
    | }
sayhello: ()Unit

Now, let’s call it.

scala> sayhello()

Hello
As you can see, since we make this function return nothing, it returns Unit. All that this Scala function does is take no parameters and simply print Hello.

c. Without = | With Parameters

We can declare a Scala function that takes parameters to work on to produce a result. Here, we simply print that result instead of returning it.

scala> def sum(a:Int,b:Int)
    | {
    | println(a+b)
    | }
sum: (a: Int, b: Int)Unit
scala> sum(2,5)

7
This code prints the sum of two integers. By default, this Scala function returns Unit.

d. With = | Without Parameters

With the = operator, a function takes a return type, and also returns a value of that type.

scala> def func():Int={
    | return 7
    | }
func: ()Int
In Scala, if you type in the same commands again, it will detect that:
scala> scala> def func():Int={
// Detected repl transcript. Paste more, or ctrl-D to finish.
 | return 7
    | }
func: ()Int

To break out of this, press Ctrl+D.
// Replaying 1 commands from transcript.

scala> def func():Int={
return 7
}
func: ()Int
scala>

Note that this, however, wouldn’t work:

scala> def func()={
    | return 7
    | }
<console>:15: error: method func has return statement; needs result type
      return 7
      ^

e. With = | With Parameters

Let’s try defining a Scala function to work on some parameters to return a result.

scala> def sum(a:Int,b:Int):Int={
    | return a+b
    | }
sum: (a: Int, b: Int)Int
scala> sum(2,5)
res22: Int = 7

This would’ve worked too:

scala> def sum(a:Int,b:Int):Int={
    | println("Adding")
    | a+b
    | }
sum: (a: Int, b: Int)Int
scala> sum(2,5)
Adding
res23: Int = 7

This means that a function will return the value of the expression right before the closing curly brace; the ‘return’ keyword isn’t necessary.

Learn: Scala DataTypes with Syntax and Examples

4. Recursion in Scala Function

A Scala function involves in recursion when it makes a call to itself. Let’s take an example:

scala> def factorial(n:Int):Int={
   | if(n==1)
    | {
    | return 1
    | }
    | n*factorial(n-1)
    | }
factorial: (n: Int)Int
scala> factorial(6)
res0: Int = 720
scala> factorial(1)
res1: Int = 1
scala> factorial(4)
res2: Int = 24
scala> factorial(10)
res4: Int = 3628800

This Scala  function correctly calculates the factorial of an integer one or greater.
Learn: Scala Comments with Syntax and Example

5. Default Arguments in Scala

If we elide an argument in a function call, Scala will take the default value we provided for it.

scala> def func(a:Int,b:Int=7){
    | println(a*b)
    | }
func: (a: Int, b: Int)Unit
scala> func(2,5)
10
scala> func(2)

14
But make sure that any default arguments must be after all non-default arguments. The following code raises an error:

scala> def func(a:Int=7,b:String){
    | println(s"$a $b")
    | }
func: (a: Int, b: String)Unit
scala> func("Ayushi")
<console>:13: error: not enough arguments for method func: (a: Int, b: String)Unit.
Unspecified value parameter b.
      func("Ayushi")
          ^

Learn: Scala String: Creating String, Concatenation, String Length

6. Scala Named Arguments

When we want to pass arguments to a Scala function in a different order, we can pass them with names:

scala> def diff(a:Int,b:Int):Int={
    | return b-a
    | }
diff: (a: Int, b: Int)Int
scala> diff(2,3)
res12: Int = 1
scala> diff(b=3,a=2)
res13: Int = 1

Learn: Scala Arrays and Multidimensional Arrays in Scala

7. Scala Functions with Variable Arguments

When we don’t know how many arguments we’ll want to pass, we can use a variable argument for this:

scala> def sum(args:Int*):Int={
    | var result=0
    | for(arg<-args){
    | result+=arg
    | }
    | result}
sum: (args: Int*)Int
Let’s try calling this with different number of arguments.
scala> sum(1)
res0: Int = 1
scala> sum(2,3)
res1: Int = 5
scala> sum(4,5,2,7)
res2: Int = 18

8. Higher-Order Functions in Scala

Since Scala is a highly functional language, it treats its functions as first-class citizens. This means that we can pass them around as parameters, or even return them from functions.

Let’s first define a Scala function sayhello:

scala> def sayhello(s:String){
    | println(s"Hello, $s")
    | }
sayhello: (s: String)Unit
Suppose we have a string ‘name’:
scala> val name:String="Ayushi"
name: String = Ayushi

Now, let’s define a function func that calls ‘sayhello’ on ‘name’.

scala> def func(f:String=>Unit,s:String){
    | f(s)
    | }
func: (f: String => Unit, s: String)Unit
scala> func(sayhello,name)

Hello, Ayushi
In this example, we used a Scala function as a parameter to another.

Learn: Tuples in Scala – A Quick Introduction

9. Nested Functions in Scala

With Scala, we can define a Scala function inside another. This is what a local function looks like:

scala> def outer(){
    | println("In outer")
    | def inner(){
    | println("In inner")
    | }
    | inner()
    | }
outer: ()Unit
scala> outer()

In outer
In inner
Let’s take another example.

scala> def outer(a:Int){
    | println("In outer")
    | def inner(){
    | println(a*3)
    | }
    | inner()
    | }
outer: (a: Int)Unit
Now, let’s call it:
scala> outer(3)

In outer
9

Learn: Scala Closures with Examples | See What is Behind the Magic

10. Scala Anonymous Functions

Anonymous functions in Scala is the lightweight syntax to create a function in one line of code. We’ve been using this in our articles so far. Anonymous functions are functioning literals, and at runtime, they instantiate into objects called function values.

scala> val sum=(a:Int,b:Int)=>a+b
sum: (Int, Int) => Int = $$Lambda$1116/1013657610@5bdb6ea8
scala> sum(2,3)
res3: Int = 5

Let’s take another Example.

scala> val x=()=>println("Hello")
x: () => Unit = $$Lambda$1122/1244890076@72ce8a9b
scala> x()

Hello

Scala Quiz

11. Scala Currying Functions

If a Scala function takes multiple parameters, we can transform it into a chain of functions where each takes a single parameter. We use multiple parameter lists for curried functions.

scala> def sum(a:Int)(b:Int)={
    | a+b
    | }
sum: (a: Int)(b: Int)Int
scala> sum(2)(5)

res3: Int = 7

So, this was all about Scala Functions. Hope you like our explanation.

12. Conclusion

In this blog, we discussed Scala functions, recursion, and default, named, and variable arguments. We also learned about higher-order functions, nested functions, anonymous functions, and carrying.

Reference

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.