In Previous chapter we learned about SCALA CASE CLASS and today lets check out SCALA FUNCTIONS.

Simply put a function is a block of statement which performs a specific task. One can identify small repetitive tasks that is used in once project and create functions out of them. In this way we do not need to write the same set of code multiple times rather we can just create a function and call the function wherever required.

How To Declare a Scala Function

To define a function you need start with ‘def’ keyword followed by function name , parameters , return type and body. Lets check this with an example

def function_name (parameter_list : Type) : return_type = { Body }

Let’s break it down one by one

  • def keyword – This is used to define a function. A function starts with this keyword.
  • function_name – This is the name given to the function. Remember that Scala Function name is case sensitive.
  • parameter_list – A list of parameters can be provided inside brackets ( ) . The parameters are comma separated followed by their Type. < parameter_name : Type >
  • return_type – This tells us the type of data that will be returned by a function ex:- Int, String ,List[Int] etc. If no return type is mentioned then it is assumed that it return nothing which is denoted by Unit.
  • : [colon] – We see colon used inside parameter_list and before return_type. In both cases anything mentioned after a colon is a Scala Type.
  • = [equals]– This says if a function returns any value or not. If you defined a return type but forget to use = then compiler will throw error.
  • Body – This contains the set of instructions which will be executed once a function is called.

Function definitions are flexible, lets see which are mandatory and which aren’t while declare one.

  • Obviously the def keyword and class names are mandatory.
  • If we are not returning any value then {: return_type =} is not required.
  • Parameters in a function are optional.
  • If you have a return value then return_type is optional but = sign is mandatory. This is possible because of Type Inference.

How to Call a Scala Function

Calling a function is similar to other programming languages function calls.

  • If the function is stand-alone then you can call it directly by its name.
def prt(name: String){
  • If the function is inside a Singleton Object then we need to call like object_name.function_name
scala> object student{
                  def prt(x: String){
defined object student

scala> student.prt("Smith")

Scala Functions Default Arguments

You can assign default values to input parameters in case the user fails to provide a value .

Use Case

Lets say we have a function which takes first_name and last_name as parameters and prints the name. What if the last_name is not mandatory and when last_name is not provided then the function call should not fail. In such cases we use Default Arguments. Lets see how to do it.

scala> def name(fname:String ,lname:String = "Unknown" ){ println(s"$fname $lname")}
name: (fname: String, lname: String)Unit

scala> name("Kevin","Hart")
Kevin Hart

scala> name("Kevin")
Kevin Unknown

Scala Functions Named Arguments

Its always good to call a function using named arguments. Using this we can pass the parameters while calling a function in any order.Lets check it with an example.

scala> def name(fnm:String ,lnm:String) ={ println($"$fnm $lnm") }
name: (fnm: String, lnm: String)Unit

scala> name(lnm= "Hart" ,fnm= "Kevin")
Kevin Hart

Note that all the default arguments should be placed after all the non-default argument.

Use Case

It may so happen that a developer while making changes to an existing function changes the sequence of parameters. For example for some reason the developer changes the sequence and now the function is def name(lnm:String , fnm:string).

Now when you call the function it doesn’t fail but instead of showing Kevin Hart, now it displays Hart Kevin. In a more serious scenario the function call might totally fail. So in case you are using named arguments you will always pass the parameters correctly even if the sequence is changed.

Scala Functions with Variable Arguments

If you are not sure how many arguments the user is going to input then you can use varargs field by adding a * after the field type. This makes the function more flexible. Lets check this with an example, suppose you need to create a function which takes in any number of words and simply prints them one by one. In this case as you are not sure how many arguments the user will supply you can use varargs field as the input parameter.

scala> def prt(name: String*){
     | for(x <- name){println(x)}
     | }
prt: (name: String*)Unit

scala> prt("Scala","Tutorial")

scala> prt("Scala","Function","Tutorial")

As you see above prt is a function which takes in varargs field of type String*. And it works when you pass different number of parameters.

Use Case

The use case for this is pretty straight forward, when the number of input arguments are not fixed, we use this. But there are few limitations which you need to keep in mind while using this.

  • First, there can only be one varargs field. What it means is you cannot have this def prt( x:Int* , y:Int*).
  • Second, you can use varargs with any number of regular field but the varargs field should always be the last parameter. Else you will get this error [error: *-parameter must come last]

Difference between Scala Function and Method

They both are almost same, it just that when a function is present inside a Class / Object / Trait they are called Methods. Also few more definitions are below

  • Procedure – When a function does not return anything or its return type is :Unit .
  • Local Function – Functions defined inside other function.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.