Scala: Functions Cheat Sheet

Function Declarations

def functionName ([list of parameters]) : [return type]

Function Definitions

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

Calling Functions

functionName( list of parameters )

In the Second way, a user can also call the function with the help of the instance and dot notation as follows:

[instance].function_name(paramter_list)

Functions Call-by-Name

def callByValue(x: Int)

Nested Functions

def FunctionName1( perameter1, peramete2, ..) = {
def FunctionName2() = {
// code
}
}

Partially Applied Functions

val multiply = (a: Int, b: Int, c: Int) => a * b * c

// less arguments passed
val f = multiply(1, 2, _: Int)

Named Arguments

Function Definition : def createArray(length:int, capacity:int);
Function calling : createArray(capacity=20, length:10);

Recursion Functions

Example:

// Scala program of factorial using recursion
 
// Creating object
object sample
{
   // Function define
   def fact(n:Int): Int=
   {
      if(n == 1) 1
      else n * fact(n - 1)
   }
 
   // Main method
   def main(args:Array[String])
   {
      println(fact(3))
   }
}

=> Output

6

Higher-Order Functions

Example:

object Demo {
   def main(args: Array[String]) {
      println( apply( layout, 10) )
   }

   def apply(f: Int => String, v: Int) = f(v)

   def layout[A](x: A) = x.toString()
}

=> Output

10

Anonymous Functions 

(z:Int, y:Int)=> z*y
Or
(_:Int)*(_Int)

Currying Functions

def function name(argument1, argument2) = operation

Leave a Reply

Your email address will not be published. Required fields are marked *