Scala Functions

Function : A function is computational unit in a program.

Function :
  • To define a function specify - name, parameter, body and return type.  
  • Functions are implicitly declared as abstract if leave off the equal sign and method body.
  • Remove = sign if not to return any thing.
  • A function can have named and optional parameters.
  • Use Unit if the function does not return anything. (Unit is equivalent to Void in java)
Function definition : def functionName ([list of parameters]) : [return type]
     
      Abstract Function : Ex - def calculation (a:Int, b:String)
      Non Abstract Function :  def functionName ([list of parameters]) : [return type] = { }
      
      Example -
  
   def calculation(a: Int, b: Int): Int = {
    var sum: Int = 0
    sum = a + b
    return sum
   }

Function Recursion:
  • Head Recursion
  • Tail Recursion
Head Recursion:
  • It stores result values in stack which may cause stack overflow exception.
         Example - Getting factorial of a number using head recursion function.
      def factorial(n: Int): Int = {
       if (n == 01 else n * factorial(n - 1)
      }

      Println(factorial(4))

Tail Recursion
  • A function in which the last action/statement is the call to the recursive function is called tail function. 
  • The function may be calling the same function of some other recursive function defined in it.
  • Tail Recursion is the specialized type of recursion that doesn't stores values in stack memory.
  • The benefit of tail recursion is it avoids the possibility of stack memory overflow exception.
          Example - Getting factorial of a number using tail recursion function.

     def factorial(n: Int): Int = {
     // @tailrec
      def iter(x: Int, result: Int): Int =
       if (x == 0) result
       else iter(x-1, result * x)
       iter(n, 1)
      }

     Println(factorial(4))
        }

N.B - This tag @tailrec in Scala ensure the function is tail recursive. If the annotation is given and if the implementation is not rail recursive then it will throw an error.

Different between function and method in functional programming :

Comments

Popular posts from this blog

Null check of Object and Object Chain in Java

Scala

Functional Programming