Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the responsive-lightbox domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114

Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the hueman domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114
Scala Functions - Testingpool

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...