Saturday, 11 May 2019

Function in Scala

Function

A function is a group of statements that perform a task. You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically, the division usually is so that each function performs a specific task.

Function Declarations
def funcName ([list of parameters]) : [return type]

Syntax:
def functionName ([list of parameters]) : [return type] = {
   function body
   return [expr]
}

Eg:
def sumDigit(a:Int,b:Int) : Int ={
            var c = a+b
            return c
}

Function call
sumDigit(10,12)                                           //Not storing value in any variable
var sumOfNumber = sumDigit(10,12)          //After returning value, storing it in variable

A function, that does not return anything can return a Unit that is equivalent to void in Java.
If a function is being called using an instance of the object, then we would use dot notation
Eg :
[instance].funcName( list of parameters )

Parameterized Function
when using parameterized function you must mention type of parameters explicitly otherwise compiler throws
an error and your code fails to compile.
def main(args: Array[String]) = {  
        functionExample(10,20)   
      }  
      def functionExample(a:Int, b:Int) = {  
          var c = a+b  
   println(c)  
}  

//Examples
Below function will not return anything as return type is not mentioned.
def fifth(test_arr:Array[Int],test_map:Map[Int,String]) : Unit =
{
  println("array length " + test_arr.length)
  println("map length " + test_map.size)       
}
fifth(Array(1,2,3,4,5),Map(1->"aakash",2->"kumar"))
//Output
5
2

//Below Return_Array function will return Array as return type mentioned as Array of Integer.
def Return_Array() : Array[Int] =
{
   var test_arr:Array[Int] = Array(1,2,3,4,5)
   return test_arr
}
var res_arr =  Return_Array()
res_arr.length

//Output 
res_arr: Array[Int] = Array(1, 2, 3, 4, 5)
5

//Below Return_Map function will return Map as return type mentioned as Map.
def Return_Map() : Map[Int,String] =
{
   var test_map:Map[Int,String] = Map(1->"aakash",2->"kumar",3->"kumar",4->"bihar")
   return test_map
}
var res_map =  Return_Map()
res_map.get(3).get
//Output
res_map: Map[Int,String] = Map(1 -> aakash, 2 -> kumar, 3 -> kumar, 4 -> bihar)
kumar

No comments:

Post a Comment

Use filter method to filter a Scala collection

Use filter method to filter a Scala collection To use filter on your collection, give it a predicate to filter the collection elements as...