Sunday, August 28, 2016

Function : Syntax

/*
   Basic Structure of a Function
   Type Annotation for Function Parameter...
      + Is Mandatory and is not Inferred
   Type Annotation for Result Type...
      +  Is Mandatory if the Function is recursive #69
      +  Optional is the Function is not recursive
   An expression in the Last statement(in this case
   x + y...will be considered as a return value and no
   mandatory 'return' keyword is needed as in Java

*/
def sum(x: Int, y: Int) : Int = {
   x + y
}
sum(9, 10)

/*
   Type Annotation for the Result Type is
   optional if function is not a Recursive function #69
   Recommended :  It is always recommended to include
                  the Return/Result type to make the code
                  readable #69
*/
def sum(x: Int, y: Int) = {
   x + y
}

/*
   For a function that contains only a single statement
   Curly braces is Optional
*/
def sum(x: Int, y: Int) = x + y
scala> /*
     |    Basic Structure of a Function
     |    Type Annotation for Function Parameter...
     |       + Is Mandatory and is not Inferred
     |    Type Annotation for Result Type...
     |       +  Is Mandatory if the Function is recursive #69
     |       +  Optional is the Function is not recursive
     |    An expression in the Last statement(in this case
     |    x + y...will be considered as a return value and no
     |    mandatory 'return' keyword is needed as in Java
     | */
     | def sum(x: Int, y: Int) : Int = {
     |    x + y
     | }
sum: (x: Int, y: Int)Int

scala> sum(9, 10)
res9: Int = 19

scala> 

scala> /*
     |    Type Annotation for the Result Type is
     |    optional if function is not a Recursive function #69
     |    Recommended :  It is always recommended to include
     |                   the Return/Result type to make the code
     |                   readable #69
     | */
     | def sum(x: Int, y: Int) = {
     |    x + y
     | }
sum: (x: Int, y: Int)Int

scala> 

scala> /*
     |    For a function that contains only a single statement
     |    Curly braces is Optional
     | */
     | def sum(x: Int, y: Int) = x + y
sum: (x: Int, y: Int)Int

Unit : A method which do not return any result is indicated by 'Unit' type
Side Effect :  A method that returns Unit is only executed for its Side effect
scala> def hello() = println("This is hello world")
hello: ()Unit

Note : The Method Parameters are always 'val' #102

Reference : #70