Tutorials
scala

Basics of Functions and Methods in Scala

Learn about the basics of methods, named arguments, default parameter values, variable arguments in addition to different kinds of functions.

Interested in learning more about Scala? Take DataCamp's Introduction to Scala course.

Scala is a functional programming language where it contains both functions as first-class values and methods and has both similarities and dissimilarities. Both the functions and methods are a block of the reusable code also used to store the repeated code in one place, which makes a function call to performs a particular specific task. They also make code easier to debug and modify.

However, functions are an object which is initialized in a variable, but methods start with the 'def' keyword followed by the method name, parameter list, method body with the return value.

You'll be learning the following topics:

  1. Method declaration and definition
  2. Method Call
  3. A method with named arguments
  4. Default Parameter Values
  5. Variable-length Arguments
  6. Recursion Function
  7. Anonymous Function

Method declaration and definition

The syntax for method declaration and definition in Scala is below:

def 'method_name' ('parameters':'return_type_parameters') : ('return_type_of_method') = {
    'method_body'
     return 'value'
}

The method in Scala starts with the following parts:

  1. 'def': keyword which is used to declare methods.
  2. 'method_name': is the name of your method, which is in lower camel case.
  3. 'parameters': is method parameters that may have no parameter or one parameter only but are separated by a comma when there is more than one parameter.
  4. 'return_type_of_parameters': need to match according to the data type of 'parameters_list' and is compulsory
  5. 'return_type_of_method': is optional, but in default, 'Unit' is returned, but the value can be returned with 'return' keyword.
  6. Assignment Symbol('='): is optional, and if used will assign the return value and not using it will make the method not to return anything.
  7. 'method_body': is the block of code enclosed inside curly braces '{}' and consists of the required logic or certain task or operations.
  8. return: is the keyword used to return the required values and also terminate the program but is rarely used in Scala.

Method call

The syntax for Method call in Scala is below:

    method_name(arguments)

The Method call can be quickly done by 'method_name', which is the name of the corresponding method that you want to call with the arguments is passed.

A method with named arguments

The method with named arguments will allow passing the argument to the methods' parameter during the method call where each of the arguments is matched one by one to the method parameters. You will see the example below of passing the arguments with Function declaration and definition along with the method call in action:

object calculateResult {
      def funSub(x:Int, y:Int) : Int =
   {

       var diff:Int = 0
       diff = x - y

       // return value
       return diff
   }
   def main(args: Array[String]) {

      // Function call
      println("Difference of the value is: " + funSub(8,6));
      println("Difference of the value is " + funSub(y=6,x=8));
   }
}

The above program gives the output as:
Difference of the value is: 2
Difference of the value is: 2

The above program contains an object 'calculateResult', and inside it contains a method named as 'funSub' with both the parameters x and y having return type as 'Int,' the overall return type of the method is 'Int'. It is followed by an assignment statement to assign the return value. The curly braces indicate the start of the method body, where the variable 'diff' is initialized with the initial value of 0. The Method call 'funSub(8,6)' done in the main method matches 8 to 'x' and 6 to 'y,' and the subtraction operation is carried out, and the value of 'diff' is returned and finally gets printed. Similarly, the 'funSub(x=8,y=6)' matches 6 to 'y' and 8 to 'x' to parameters in the method during method call where the order doesn't matter where a similar operation is done and is return and result gets printed out.

Default Parameter Values

You can specify the default values for the method parameters through the initialization of corresponding values and can leave the method call empty by not passing the argument.

object calculateResult {
      def funSub(x:Int=9, y:Int=6) : Int =
   {

       var diff:Int = 0
       diff = x - y

       // return value
       return diff
   }
   def main(args: Array[String]) {

      // Function call
    print( "The final value is: " + funSub() );

   }
}

The above program gives the output as:
The final value is: 3

You can see the above program contains object defined as 'calculateResult' and inside that there is a method named as 'funSub' with the parameters x and y with both having return type as 'Int' and the overall return type of the method is 'Int' and is followed by assignment statement which will assign the return value. The curly braces indicate the start of the method body, where the variable 'diff' is initialized with the initial value of 0. The Method call is done inside from the main method where 'funSub()' calls and initialize the x to 9 and y to 6, and the operation is carried out, which makes the value 'diff' to be returned and printed.

Variable-length Arguments

Variable-length Arguments are the arguments that take any variable number of arguments and can be passed by the user or client. The last parameter in the method is declared using '*' which needs to be repeated.

object variableArgument {
    def main(args: Array[String]) {
       printAll("Scala", "is", "great")
    }

    def printAll(strings: String*) {
        var i : Int = 0;

      for( value <- strings ){
         println(value);
         i = i + 1;
      }
    }
}

The above program gives the output as:
Scala
is
great

You can see the above program contains an object 'variableArgument' with 'printAll' methods where variable-length argument 'String*' is defined at the end and during the call of a method a list of strings can be passed. The passed list of strings is looped over and shown as output inside the primary function.

Recursion Function

Recursion is the technique used in functional programming where the problem is solved by repeatedly breaking it into smaller subproblems, which are similar to the original problem. The more minor problems are solved, and their solutions are applied to get the solutions for the original problem. So, it is called a divide-and-conquer or decrease-and-conquer problem, which makes the code to be clean and elegant. When writing a recursive function, the two points need to be considered strictly. They are:

  • Base case: There might be more than one base case in a function that needs to find out otherwise might lead to infinite recursion. It needs to have a solution, i.e., the simple form of output or solution that can be achieved without recursion.
  • Recursive case: The case where the recursive function is applied i.e.recursive call are being made. The main crux of the problem is that in each recursive call, the size needs to decrease i.e.problem needs to be divided into smaller sub-problems until you reach the base case. At last, you combine the solution to get the main problem, which is called a divide-conquer approach.

The factorial of any given number is n! It can be mathematically expressed as follows:

n! = n.(n-1).(n-2)...3.2.1

Also, you can make the terms (n-1).(n-2)...3.2.1 to be (n-1)! So, the factorial of any given number is always n. (n-1)!

Now you can see below the recursive way of solving the problem.

object factorialDemo {
   def main(args: Array[String]) {
      for (i <- 1 to 5)
         println( "Factorial of " + i + ": = " + factorial(i) )
   }

   def factorial(n: Int): Int = {  
      if (n <= 1)
         return 1  
      else    
      return n * factorial(n - 1)
   }
}

The above program give the output as:
Factorial of 1: = 1
Factorial of 2: = 2
Factorial of 3: = 6
Factorial of 4: = 24
Factorial of 5: = 120

You can see above where there is an object called 'factorialDemo' and inside it, there is a 'main' function containing a loop which repeats over for five times and also includes a function call to 'factorial' where recursive function makes a recursive call, i.e., n to five times. It stops at the base case when n becomes less than or equal to 1, and the result is returned and printed.

Anonymous Function

Anonymous Function is those lightweight function definition which doesn't have a name and is known to be function literal in Scala.

Syntax with example for Anonymous Function are as follows:

  • The first syntax and an example for Anonymous function is:
  • Syntax:

    ('first_variable':'data_type', 'second_variable':'data_type') => "certain_expression"
    

    Example:

    (var1:String:var2:String) => var1 + var2
    

    OR

  • The second syntax and an example for Anonymous function is:
  • Syntax:

     (_:'data_type')operator(_'data_type')
    

    Example:

     (_:String)+(_:String)
    

    The first syntax shows that expression after "=>" evaluates to a particular value whereas a list of the variable before "=>" used for evaluating the expression.

    The second syntax above works like a placeholder where it accepts the value as a 'wild card' character only once, and then the operator is operated among them.

    You'll see an example of anonymous function below:

     object anonymousDemo  
    {
        def main(args: Array[String])  
        {
    
    
            var function1 = (var1:Int, var2:Int) => var1 + var2
            var function2 = (_:Int) + (_:Int)
    
            // function call
            println(function1(5, 5))
            println(function2(7, 3))
        }
    }
    
    Initializing Scala interpreter ...
    
    
    
    Spark Web UI available at http://DESKTOP-03TH7J0:4040
    SparkContext available as 'sc' (version = 2.4.3, master = local[*], app id = local-1566986265958)
    SparkSession available as 'spark'
    
    
    
    
    <console>:10: error: unbound placeholder parameter
    
            var function2 = {_:Int} + {_:Int}
    
                             ^
    
    <console>:10: error: unbound placeholder parameter
    
            var function2 = {_:Int} + {_:Int}
    
                                       ^
    

    The above program gives the output as:
    10
    10

    You can see above the object named to be 'anonymousDemo' with the 'main' function containing two anonymous functions. They are syntactically different but can produce the same result, where 'function'1 evaluates by taking parameters from a function call as it is being called—passing the values 5 and 5, which results in output to be printed as 10 whereas 'function2' is also called passing 7 and 3 where it receives the value once, which accepts any valid 'Integer'. In your case, do the addition operation and output the result.

    Conclusion

    Congratulation, you've finished reading this tutorial.

    There are many advanced topics in Scala such as higher-order functions, nested function, currying function, etc.

    Reference:
    TOUR OF SCALA BASICS
    Scala | Functions – Basics
    Scala - Functions
    Anonymous Functions in Scala

    Check out DataCamp's Introduction to Scala course.

    Want to leave a comment?