JAVA DEVELOPER SITE
 

Scala - Functions


In scala, functions are first class values. You can store function value, pass function as an argument and return function as a value from other function.

Scala has both functions and methods and we use the terms method and function interchangeably with a minor difference.

Scala Function Declaration Syntax

 
  1. def functionName(parameters : typeofparameters) : returntypeoffunction = {  
  2. // statements to be executed  
  3. }  
In the above syntax, = (equal) operator is looking strange but don't worry scala has defined it as:

Calling Functions

Scala provides a number of syntactic variations for invoking methods. Following is the standard way to call a method
functionName( list of parameters )

Scala Parameterized Function Example

when using parameterized function you must mention type of parameters explicitly otherwise compiler throws an error and your code fails to compile.

  1. object MainObject {  
  2.    def main(args: Array[String]) = {  
  3.         functionExample(47,7)   
  4.     }  
  5.     def functionExample(a:Int, b:Int) = {  
  6.           var c = a+b  
  7.           println(c)  
  8.     }  
  9. }  
Output: 55

Scala Recursion Function

In scala, you can create recursive functions also. Be careful while using recursive function. There must be a base condition to terminate program safely.
object MainObject {  
  •    def main(args: Array[String]) = {  
  •         var result = functionExample(15,2)   
  •         println(result)  
  •     }  
  •     def functionExample(a:Int, b:Int):Int = {  
  •         if(b == 0)          // Base condition  
  •          0  
  •         else  
  •          a+functionExample(a,b-1)  
  •     }  
  • }  
  • Scala Function Named Parameter Example

    In scala function, you can specify the names of parameters during calling the function. object MainObject {  
  •    def main(args: Array[String]) = {  
  •         var result1 = functionExample(a = 15, b = 2)    // Parameters names are passed during call  
  •         var result2 = functionExample(b = 15, a = 2)    // Parameters order have changed during call  
  •         var result3 = functionExample(15,2)             // Only values are passed during call  
  •         println(result1+"\n"+result2+"\n"+result3)  
  •     }  
  •     def functionExample(a:Int, b:Int):Int = {  
  •         a+b  
  •     }  
  • }   Output 17 17 17