SlideShare a Scribd company logo
   Functions In Scala  


                                         Janmejani
                                     Software Consultant    
                                    Knoldus Software LLP
AGENDA
●
    What is Functions.

●
    Local Functions.

●
    First Class Function

●
    Placeholders

●
    Partially Applied Functions

●
    Closures

●
    Repeated Parameters

●
    Tail Recursion
What is Function
➢
    A function is a group of statements that together perform a task.

➢
    When program gets larger, you need some way to divide them
    into smaller more manageable pieces.

➢
    How you divide is up to you, but logically each function perform
     a specific task.
Difference Between Functions And
                   Methods
    Functions                       Methods
➢
    Functions have independent      ➢
                                        Methods do not have
    existence means they can be         independent existence
    defined outside of the class.       they are always defined
                                        with in class.
                                    ➢
                                        Methods are called using
➢
    Functions are called                instance or object.
    independently.
Functions Declaration And Definition

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

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

def addInt( a:Int, b:Int ) = {
    var sum = 0
    sum = a + b
    sum
  }
Calling Functions
Following is the standard way to call a
method:

object Test {
   def main(args: Array[String]) {
   println( "Returned Value : " + addInt(5,7) )
   }

    def addInt( a:Int, b:Int ) : a+b
}
Local Functions

Scala allows you to define functions inside a function are called local
functions.

    def factorial(i: Int): Int = {
      def fact(i: Int, factor: Int): Int = {
        if (i <= 1)
           factor
        else
           fact(i - 1, i * factor)
      }
      fact(i, 1)
    }
}
First Class Functions

Scala supports first-class functions,which means you can express
functions in function literal syntax,

 ie. , (x: Int) => x + 1,

A function literal is compiled into a class that when instantiated at run-
time is a function value.

 For eg :

   var increase = (x: Int) => x + 1

   increase(10)
Functions Applied On Functions

foreach:

   It takes a function as an argument and invokes that function on each of
   its elements.

For eg:
           val someNumbers = List(-11, -10, -5, 0, 5, 10)

           SomeNumbers foreach((x: Int) => println(x))
Filters:

   Scala provides a number of ways to leave out redundant information.

   This method selects those elements of a collection that pass a test the
   user supplies.

       For eg:
          someNumbers.filter(x => x > 0)

           someNumbers.filter(_> 0)

   To make a function literal even more concise, you can use underscores
   as placeholders for one or more parameters, so long as each parameter
   appears only one time within the function literal.
Partially Applied Functions
Replace the entire list of parameter.
 For example, rather than writing println(_), you could write println _.

   val someNumbers = List(-11, -10, -5, 0, 5, 10)

   someNumbers.foreach(println _)

A partially applied function is an expression in which you don’t supply all of
the arguments needed by the function. Instead, you supply some, or none, of
the needed arguments.
Closures
 A closure is a function whose return value depends on the value of one or
more variables declared outside this function.
  For eg:
    val multiplier = (i:Int) => i * 10
➢
  A statement with no free variable is called close term.

    val multiplier = (i:Int) => i * factor
➢
  A statement with free variable is called open term.

factor is a free variable
i is a bound variable

The function value (the object) that’s created at runtime from this function
literal is called a closure.
REPEATED PARAMETERS
Scala allows you to indicate that the last parameter to a function may be
Repeated.

This allows clients to pass variable length argument lists to the
Function.

 For eg:
      def Size(is: Int*) = is.length
      println(Size(2,3,4,5,6,67))

To denote a repeated parameter, place an asterisk after the type of
the parameter.
Tail Recursion
In order for a recursive call to be tail recursive, the call back to the function
must be the last action performed in the function.

   def factorial(number:Int) : Int = {
    if (number == 1)
    return 1
        number * factorial (number - 1)
        }
   println(factorial(5))

This is not a tail recursive Function, because the total returned from the
recursive call is being multiplied by number, the recursive call is NOT the
last action performed in the function.
To take this example and make it tail recursive, we must make sure that last
             action performed in the function is the recursive call.


def factorial(fact: Int, number: Int) : Int = {
        if(number == 1)
         return fact
        factorial(number * fact, number - 1)
}
print(factorial(1,5))
Why Tail Recursion?

In the recursion example, notice how the result of each call must be
remembered, to do this each recursive call requires an entry on the stack
until all recursive calls have been made. This makes the recursive call more
expensive in terms of memory.

While in the tail recursive example, there are no intermediate values that
need to be stored on the stack, the intermediate value is always passed back
as a parameter.
Scala functions

More Related Content

What's hot

Functions in C++
Functions in C++Functions in C++
Functions in C++
Mohammed Sikander
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
SIVASHANKARIRAJAN
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
Prof. Dr. K. Adisesha
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
Vineeta Garg
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
Praveen M Jigajinni
 
Decision Making & Loops
Decision Making & LoopsDecision Making & Loops
Decision Making & Loops
Akhil Kaushik
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Nikhil Pandit
 
What is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | EdurekaWhat is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | Edureka
Edureka!
 
Inline functions
Inline functionsInline functions
Inline functions
DhwaniHingorani
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
Vraj Patel
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overriding
Rajab Ali
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
Kuppusamy P
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
Madishetty Prathibha
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)
Scott Wlaschin
 
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Samuel Fortier-Galarneau
 
Function Pointer
Function PointerFunction Pointer
Function Pointer
Dr-Dipali Meher
 
Python programming : Abstract classes interfaces
Python programming : Abstract classes interfacesPython programming : Abstract classes interfaces
Python programming : Abstract classes interfaces
Emertxe Information Technologies Pvt Ltd
 

What's hot (20)

Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Constructor
ConstructorConstructor
Constructor
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Decision Making & Loops
Decision Making & LoopsDecision Making & Loops
Decision Making & Loops
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
What is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | EdurekaWhat is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | Edureka
 
Inline functions
Inline functionsInline functions
Inline functions
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overriding
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)
 
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
 
Function Pointer
Function PointerFunction Pointer
Function Pointer
 
Inheritance
InheritanceInheritance
Inheritance
 
Python programming : Abstract classes interfaces
Python programming : Abstract classes interfacesPython programming : Abstract classes interfaces
Python programming : Abstract classes interfaces
 

Similar to Scala functions

Functions & closures
Functions & closuresFunctions & closures
Functions & closures
Knoldus Inc.
 
Functions & Closures in Scala
Functions & Closures in ScalaFunctions & Closures in Scala
Functions & Closures in Scala
Knoldus Inc.
 
Functions & Closures in Scala
Functions & Closures in ScalaFunctions & Closures in Scala
Functions & Closures in Scala
Neelkanth Sachdeva
 
Python Session - 4
Python Session - 4Python Session - 4
Python Session - 4
AnirudhaGaikwad4
 
Intro f# functional_programming
Intro f# functional_programmingIntro f# functional_programming
Intro f# functional_programming
Mauro Ghiani
 
Lecture 11 - Functions
Lecture 11 - FunctionsLecture 11 - Functions
Lecture 11 - Functions
Md. Imran Hossain Showrov
 
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONSINTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
KalaivaniD12
 
Functional Objects in Ruby: new horizons – Valentine Ostakh
Functional Objects in Ruby: new horizons  – Valentine OstakhFunctional Objects in Ruby: new horizons  – Valentine Ostakh
Functional Objects in Ruby: new horizons – Valentine Ostakh
Ruby Meditation
 
All About ... Functions
All About ... FunctionsAll About ... Functions
All About ... Functions
Michal Bigos
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx
Manas40552
 
Python functions part12
Python functions  part12Python functions  part12
Python functions part12
Vishal Dutt
 
10. funtions and closures IN SWIFT PROGRAMMING
10. funtions and closures IN SWIFT PROGRAMMING10. funtions and closures IN SWIFT PROGRAMMING
10. funtions and closures IN SWIFT PROGRAMMING
LOVELY PROFESSIONAL UNIVERSITY
 
Functional programming in clojure
Functional programming in clojureFunctional programming in clojure
Functional programming in clojure
Juan-Manuel Gimeno
 
Functional programming java
Functional programming javaFunctional programming java
Functional programming java
Maneesh Chaturvedi
 
functionnotes.pdf
functionnotes.pdffunctionnotes.pdf
functionnotes.pdf
AXL Computer Academy
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
SulekhJangra
 
Functional programming 101
Functional programming 101Functional programming 101
Functional programming 101
Maneesh Chaturvedi
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
MikialeTesfamariam
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programs
GeethaPanneer
 

Similar to Scala functions (20)

Functions & closures
Functions & closuresFunctions & closures
Functions & closures
 
Functions & Closures in Scala
Functions & Closures in ScalaFunctions & Closures in Scala
Functions & Closures in Scala
 
Functions & Closures in Scala
Functions & Closures in ScalaFunctions & Closures in Scala
Functions & Closures in Scala
 
Python Session - 4
Python Session - 4Python Session - 4
Python Session - 4
 
Intro f# functional_programming
Intro f# functional_programmingIntro f# functional_programming
Intro f# functional_programming
 
Lecture 11 - Functions
Lecture 11 - FunctionsLecture 11 - Functions
Lecture 11 - Functions
 
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONSINTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
 
Functional Objects in Ruby: new horizons – Valentine Ostakh
Functional Objects in Ruby: new horizons  – Valentine OstakhFunctional Objects in Ruby: new horizons  – Valentine Ostakh
Functional Objects in Ruby: new horizons – Valentine Ostakh
 
All About ... Functions
All About ... FunctionsAll About ... Functions
All About ... Functions
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx
 
Python functions part12
Python functions  part12Python functions  part12
Python functions part12
 
10. funtions and closures IN SWIFT PROGRAMMING
10. funtions and closures IN SWIFT PROGRAMMING10. funtions and closures IN SWIFT PROGRAMMING
10. funtions and closures IN SWIFT PROGRAMMING
 
Functional programming in clojure
Functional programming in clojureFunctional programming in clojure
Functional programming in clojure
 
Functional programming java
Functional programming javaFunctional programming java
Functional programming java
 
functionnotes.pdf
functionnotes.pdffunctionnotes.pdf
functionnotes.pdf
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
 
Functional programming 101
Functional programming 101Functional programming 101
Functional programming 101
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programs
 

More from Knoldus Inc.

Using InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in JmeterUsing InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in Jmeter
Knoldus Inc.
 
Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)
Knoldus Inc.
 
Stakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) PresentationStakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) Presentation
Knoldus Inc.
 
Introduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) PresentationIntroduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) Presentation
Knoldus Inc.
 
Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)
Knoldus Inc.
 
Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)
Knoldus Inc.
 
Clean Code in Test Automation Differentiating Between the Good and the Bad
Clean Code in Test Automation  Differentiating Between the Good and the BadClean Code in Test Automation  Differentiating Between the Good and the Bad
Clean Code in Test Automation Differentiating Between the Good and the Bad
Knoldus Inc.
 
Integrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test AutomationIntegrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test Automation
Knoldus Inc.
 
State Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptxState Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptx
Knoldus Inc.
 
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
Knoldus Inc.
 
OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)
Knoldus Inc.
 
Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
Knoldus Inc.
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Knoldus Inc.
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
Knoldus Inc.
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
Knoldus Inc.
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
Knoldus Inc.
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
Knoldus Inc.
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
Knoldus Inc.
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
Knoldus Inc.
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
Knoldus Inc.
 

More from Knoldus Inc. (20)

Using InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in JmeterUsing InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in Jmeter
 
Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)
 
Stakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) PresentationStakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) Presentation
 
Introduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) PresentationIntroduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) Presentation
 
Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)
 
Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)
 
Clean Code in Test Automation Differentiating Between the Good and the Bad
Clean Code in Test Automation  Differentiating Between the Good and the BadClean Code in Test Automation  Differentiating Between the Good and the Bad
Clean Code in Test Automation Differentiating Between the Good and the Bad
 
Integrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test AutomationIntegrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test Automation
 
State Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptxState Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptx
 
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
 
OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)
 
Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 

Scala functions

  • 1.    Functions In Scala    Janmejani                                      Software Consultant          Knoldus Software LLP
  • 2. AGENDA ● What is Functions. ● Local Functions. ● First Class Function ● Placeholders ● Partially Applied Functions ● Closures ● Repeated Parameters ● Tail Recursion
  • 3. What is Function ➢ A function is a group of statements that together perform a task. ➢ When program gets larger, you need some way to divide them into smaller more manageable pieces. ➢ How you divide is up to you, but logically each function perform a specific task.
  • 4. Difference Between Functions And Methods Functions Methods ➢ Functions have independent ➢ Methods do not have existence means they can be independent existence defined outside of the class. they are always defined with in class. ➢ Methods are called using ➢ Functions are called instance or object. independently.
  • 5. Functions Declaration And Definition def functionName ([list of parameters]) : [return type] def functionName ([list of parameters]) : [return type] = { function body return [expr] } def addInt( a:Int, b:Int ) = { var sum = 0 sum = a + b sum }
  • 6. Calling Functions Following is the standard way to call a method: object Test { def main(args: Array[String]) { println( "Returned Value : " + addInt(5,7) ) } def addInt( a:Int, b:Int ) : a+b }
  • 7. Local Functions Scala allows you to define functions inside a function are called local functions. def factorial(i: Int): Int = { def fact(i: Int, factor: Int): Int = { if (i <= 1) factor else fact(i - 1, i * factor) } fact(i, 1) } }
  • 8. First Class Functions Scala supports first-class functions,which means you can express functions in function literal syntax, ie. , (x: Int) => x + 1, A function literal is compiled into a class that when instantiated at run- time is a function value. For eg : var increase = (x: Int) => x + 1 increase(10)
  • 9. Functions Applied On Functions foreach: It takes a function as an argument and invokes that function on each of its elements. For eg: val someNumbers = List(-11, -10, -5, 0, 5, 10) SomeNumbers foreach((x: Int) => println(x))
  • 10. Filters: Scala provides a number of ways to leave out redundant information. This method selects those elements of a collection that pass a test the user supplies. For eg: someNumbers.filter(x => x > 0) someNumbers.filter(_> 0) To make a function literal even more concise, you can use underscores as placeholders for one or more parameters, so long as each parameter appears only one time within the function literal.
  • 11. Partially Applied Functions Replace the entire list of parameter. For example, rather than writing println(_), you could write println _. val someNumbers = List(-11, -10, -5, 0, 5, 10) someNumbers.foreach(println _) A partially applied function is an expression in which you don’t supply all of the arguments needed by the function. Instead, you supply some, or none, of the needed arguments.
  • 12. Closures A closure is a function whose return value depends on the value of one or more variables declared outside this function. For eg: val multiplier = (i:Int) => i * 10 ➢ A statement with no free variable is called close term. val multiplier = (i:Int) => i * factor ➢ A statement with free variable is called open term. factor is a free variable i is a bound variable The function value (the object) that’s created at runtime from this function literal is called a closure.
  • 13. REPEATED PARAMETERS Scala allows you to indicate that the last parameter to a function may be Repeated. This allows clients to pass variable length argument lists to the Function. For eg: def Size(is: Int*) = is.length println(Size(2,3,4,5,6,67)) To denote a repeated parameter, place an asterisk after the type of the parameter.
  • 14. Tail Recursion In order for a recursive call to be tail recursive, the call back to the function must be the last action performed in the function. def factorial(number:Int) : Int = { if (number == 1) return 1 number * factorial (number - 1) } println(factorial(5)) This is not a tail recursive Function, because the total returned from the recursive call is being multiplied by number, the recursive call is NOT the last action performed in the function.
  • 15. To take this example and make it tail recursive, we must make sure that last action performed in the function is the recursive call. def factorial(fact: Int, number: Int) : Int = { if(number == 1) return fact factorial(number * fact, number - 1) } print(factorial(1,5))
  • 16. Why Tail Recursion? In the recursion example, notice how the result of each call must be remembered, to do this each recursive call requires an entry on the stack until all recursive calls have been made. This makes the recursive call more expensive in terms of memory. While in the tail recursive example, there are no intermediate values that need to be stored on the stack, the intermediate value is always passed back as a parameter.