Scala Functions

When program gets larger, it needs to be divided into smaller reusable, more manageable pieces. It can be achieved by writing functions where code can be divided. Scala provides rich set of built in functions and also allows to write user defined functions in many different ways.

There are some key points, we need to learn for better understanding of functions.

  • A keyword def is used to create a function.
  • Functions are first class values. That means , we can store a function value in variable, pass functions as arguments and return functions as a value from another functions just like some integer, sequences etc.
  • Type of parameters needs to be mentioned while defining functions.More that one parameter can be passed separated by comma.
  • Return type of function is optional. Default return type is Unit.
  • If return keyword is not written to return any value from function, compiler will understand the type from the last statement or expression present in the function.

Let’s understand above points with the function syntax below.

def functionName(parameter1: TypeOfParameter,parameter2: TypeOfParameter): returnTypeOfFunction = {
  //code to be executed
}

In the above syntax, equal (=) operator is optional. If it is used, function will return a value and if it is not used, function will not return a value, rather works as a subroutine.

Example of a function:

class Person {
  def printName(): String ={  //Defining Function
    var name = "Thomas"
    name
  }
}

object emp{
  def main(args: Array[String]): Unit = {
    var e = new Person
    print(e.printName())   //Calling Function
  }
}
Output: Thomas
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...