SlideShare a Scribd company logo
1 of 24
Scala Functions & Closures




Neelkanth Sachdeva

Consultant / Software Engineer

Knoldus Software LLP , New Delhi

neelkanthsachdeva.wordpress.com

neelkanth@knoldus.com
Methods

The most common way to define a function is
as a member of some object.Such a function is
called a Method.
/*
 * Normal Functions
 */

object LongLines extends App{

    def ProcessFile(fileName: String, width: Int)
{
        val source = Source.fromFile(fileName)
        for (line <- source.getLines)
          processLine(fileName, width, line)
    }

    private def processLine(filename: String,
      width: Int, line: String) {
      if (line.length > width)
        println(filename + ": " + line)
    }
}
Local functions

Programs should be decomposed into many small functions that each
do a well-defined task. One problem with this approach is that all the
helper function names can pollute the program name space
In Java →
1.Defining private methods.
In Scala →
1. Defining private methods also works
                 +
2. You can define functions inside other functions
/*
 * Defining Local Functions More Easily
 */
object LongLines extends App {

    def ProcessFile(fileName: String,width: Int) {

        def processLine(line: String) {
          if (line.length > width)
            println(fileName + ": " + line)
        }

        val source = Source.fromFile(fileName)
        for (line <- source.getLines)
          processLine(line)
    }
}
First-class functions

Scala has first-class functions. Not only can you
define functions and call them, but you can write
down functions as unnamed literals and then
pass them around as values.
Function Literals

A function literal is compiled into a class that
when instantiated at runtime is a function value.
Then What is the difference ?
Thus the distinction between function literals and
values is that function literals exist in the source
code, whereas function values exist as objects at
runtime.
Example:

Simple function literal :-

 (x: Int) => x + 1

The => designates that this function converts the thing on the left (any
integer x) to the thing on the right (x + 1). So, this is a function mapping
any integer x to x + 1.
Function values are objects, so

→ you can store them in variables

 scala> var increase = (x: Int) => x + 1
 increase: (Int) => Int = <function>

They are functions too , so

→ you can invoke them using the usual parentheses
  function-call notation.

   scala> increase(10)
   res0: Int = 11
We've seen the nuts and bolts of function literals and function
values. Many Scala libraries give you opportunities to use
them e.g

foreach method:

scala> val someNumbers = List(-11, -10, -5, 0, 5, 10)
someNumbers: List[Int] = List(-11, -10, -5, 0, 5, 10)
scala> someNumbers.foreach((x: Int) => println(x))

filter method:

scala> someNumbers.filter((x: Int) => x > 0)
Short forms of function literals
Scala provides a number of ways to leave out redundant information and
write function literals more briefly. Keep your eyes open for these
opportunities, because they allow you to remove clutter from your code.


One way to make a function literal more brief is to leave off the parameter
types. Thus, the previous example with filter could be written like this:


scala> someNumbers.filter((x) => x > 0)
res7: List[Int] = List(5, 10)
Even leave the parentheses around x
scala> someNumbers.filter( x => x > 0)
res7: List[Int] = List(5, 10)
Placeholder syntax

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.


scala> someNumbers.filter( _ > 0)
res9: List[Int] = List(5, 10)
Partially applied functions

someNumbers.foreach( println _ )
Scala treats this short form exactly as if you had
written the following:
someNumbers.foreach(x => println(x))


When you use an underscore in this way, you are
writing a partially applied function.
Examples:



scala> def sum(a: Int, b: Int, c: Int) = a + b + c
sum: (Int,Int,Int)Int

scala> sum(1, 2, 3)
res0: Int = 6

scala> val a = sum _
a: (Int, Int, Int) => Int = <function>

scala> a.apply(1, 2, 3)
res1: Int = 6
scala> val b = sum(1, _: Int, 3)
b: (Int) => Int = <function>

scala> b(2)
res15: Int = 6

In this case, b.apply invoked sum(1, 2, 3).

scala> val c = sum

<console>:5: error: missing arguments for method sum...
follow this method with `_' if you want to treat it as
a partially applied function
val c = sum
          ˆ
Closures
x → by contrast, is a bound variable, because it
does have a meaning in the context of the
function: it is defined as the function’s lone
parameter, an Int.


more → more is a free variable, because the
Function literal does not itself give a meaning to it.
So the closures is :

The function value (the object) that’s created at
runtime from this function literal is called a
closure.
(x: Int) => x + 1, is called a closed term,
Thus a function value created at runtime from
this function literal is not a closure in the strictest
Sense .


(x: Int) => x + more, is an open term. Therefore,
any function value created at runtime from (x: Int) => x +
more will by definition require that a binding for its free
variable, more, be captured. The resulting function value,
which will contain a reference to the captured more variable,
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.
Thank You

More Related Content

What's hot

What's hot (19)

Java Script Language Tutorial
Java Script Language TutorialJava Script Language Tutorial
Java Script Language Tutorial
 
Javascript
JavascriptJavascript
Javascript
 
Namespace in C++ Programming Language
Namespace in C++ Programming LanguageNamespace in C++ Programming Language
Namespace in C++ Programming Language
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Books
BooksBooks
Books
 
Linq Introduction
Linq IntroductionLinq Introduction
Linq Introduction
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Lambdas HOL
Lambdas HOLLambdas HOL
Lambdas HOL
 
Scala oo (1)
Scala oo (1)Scala oo (1)
Scala oo (1)
 
Python functions
Python functionsPython functions
Python functions
 
Basics of Functional Programming
Basics of Functional ProgrammingBasics of Functional Programming
Basics of Functional Programming
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday life
 
Chapter 16 Dictionaries
Chapter 16 DictionariesChapter 16 Dictionaries
Chapter 16 Dictionaries
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programming
 
First approach in linq
First approach in linqFirst approach in linq
First approach in linq
 
Functions1
Functions1Functions1
Functions1
 
Pxb For Yapc2008
Pxb For Yapc2008Pxb For Yapc2008
Pxb For Yapc2008
 

Viewers also liked

Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka RemotingKnoldus Inc.
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parametersKnoldus Inc.
 
Intoduction on Playframework
Intoduction on PlayframeworkIntoduction on Playframework
Intoduction on PlayframeworkKnoldus Inc.
 
String Interpolation in Scala
String Interpolation in ScalaString Interpolation in Scala
String Interpolation in ScalaKnoldus Inc.
 
WorkingWithSlick2.1.0
WorkingWithSlick2.1.0WorkingWithSlick2.1.0
WorkingWithSlick2.1.0Knoldus Inc.
 
Akka vikas hazrati
Akka vikas hazratiAkka vikas hazrati
Akka vikas hazratiKnoldus Inc.
 
Modular programming Using Object in Scala
Modular programming Using Object in ScalaModular programming Using Object in Scala
Modular programming Using Object in ScalaKnoldus Inc.
 
FitNesse With Scala
FitNesse With ScalaFitNesse With Scala
FitNesse With ScalaKnoldus Inc.
 
Dependency injection in Scala
Dependency injection in ScalaDependency injection in Scala
Dependency injection in ScalaKnoldus Inc.
 
Reactive programming with scala and akka
Reactive programming with scala and akkaReactive programming with scala and akka
Reactive programming with scala and akkaKnoldus Inc.
 

Viewers also liked (17)

Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka Remoting
 
Traits in scala
Traits in scalaTraits in scala
Traits in scala
 
Simple build tool
Simple build toolSimple build tool
Simple build tool
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
 
Knolx session
Knolx sessionKnolx session
Knolx session
 
Intro lift
Intro liftIntro lift
Intro lift
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
 
Intoduction on Playframework
Intoduction on PlayframeworkIntoduction on Playframework
Intoduction on Playframework
 
String Interpolation in Scala
String Interpolation in ScalaString Interpolation in Scala
String Interpolation in Scala
 
WorkingWithSlick2.1.0
WorkingWithSlick2.1.0WorkingWithSlick2.1.0
WorkingWithSlick2.1.0
 
Traits inscala
Traits inscalaTraits inscala
Traits inscala
 
Akka vikas hazrati
Akka vikas hazratiAkka vikas hazrati
Akka vikas hazrati
 
Modular programming Using Object in Scala
Modular programming Using Object in ScalaModular programming Using Object in Scala
Modular programming Using Object in Scala
 
FitNesse With Scala
FitNesse With ScalaFitNesse With Scala
FitNesse With Scala
 
Dependency injection in Scala
Dependency injection in ScalaDependency injection in Scala
Dependency injection in Scala
 
Highcharts
HighchartsHighcharts
Highcharts
 
Reactive programming with scala and akka
Reactive programming with scala and akkaReactive programming with scala and akka
Reactive programming with scala and akka
 

Similar to Scala Functions & Closures: Learn about methods, local functions, function literals, closures and more

Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scalaehsoon
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala Knoldus Inc.
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and ClosuresSandip Kumar
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and ClosuresSandip Kumar
 
Python functions part12
Python functions  part12Python functions  part12
Python functions part12Vishal Dutt
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With ScalaKnoldus Inc.
 
Ti1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismTi1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismEelco Visser
 
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 OstakhRuby Meditation
 
All About ... Functions
All About ... FunctionsAll About ... Functions
All About ... FunctionsMichal Bigos
 
04_python_functions.ppt You can define functions to provide the required func...
04_python_functions.ppt You can define functions to provide the required func...04_python_functions.ppt You can define functions to provide the required func...
04_python_functions.ppt You can define functions to provide the required func...anaveenkumar4
 

Similar to Scala Functions & Closures: Learn about methods, local functions, function literals, closures and more (20)

Scala functions
Scala functionsScala functions
Scala functions
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Python functions part12
Python functions  part12Python functions  part12
Python functions part12
 
Google06
Google06Google06
Google06
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Ti1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismTi1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: Polymorphism
 
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
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
04_python_functions.ppt You can define functions to provide the required func...
04_python_functions.ppt You can define functions to provide the required func...04_python_functions.ppt You can define functions to provide the required func...
04_python_functions.ppt You can define functions to provide the required func...
 
Scala google
Scala google Scala google
Scala google
 
Python and You Series
Python and You SeriesPython and You Series
Python and You Series
 
functions.pptx
functions.pptxfunctions.pptx
functions.pptx
 
Python functions
Python functionsPython functions
Python functions
 

More from Knoldus Inc.

Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxKnoldus Inc.
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxKnoldus Inc.
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxKnoldus Inc.
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxKnoldus Inc.
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationKnoldus Inc.
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationKnoldus Inc.
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIsKnoldus Inc.
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II PresentationKnoldus Inc.
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAKnoldus Inc.
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Knoldus Inc.
 
Azure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxAzure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxKnoldus Inc.
 
The Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinThe Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinKnoldus Inc.
 
Data Engineering with Databricks Presentation
Data Engineering with Databricks PresentationData Engineering with Databricks Presentation
Data Engineering with Databricks PresentationKnoldus Inc.
 
Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Knoldus Inc.
 
NoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxNoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxKnoldus Inc.
 
Mastering Distributed Performance Testing
Mastering Distributed Performance TestingMastering Distributed Performance Testing
Mastering Distributed Performance TestingKnoldus Inc.
 
MLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxMLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxKnoldus Inc.
 
Introduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationIntroduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationKnoldus Inc.
 
CQRS with dot net services presentation.
CQRS with dot net services presentation.CQRS with dot net services presentation.
CQRS with dot net services presentation.Knoldus Inc.
 

More from Knoldus Inc. (20)

Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)
 
Azure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxAzure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptx
 
The Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinThe Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and Kotlin
 
Data Engineering with Databricks Presentation
Data Engineering with Databricks PresentationData Engineering with Databricks Presentation
Data Engineering with Databricks Presentation
 
Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)
 
NoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxNoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptx
 
Mastering Distributed Performance Testing
Mastering Distributed Performance TestingMastering Distributed Performance Testing
Mastering Distributed Performance Testing
 
MLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxMLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptx
 
Introduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationIntroduction to Ansible Tower Presentation
Introduction to Ansible Tower Presentation
 
CQRS with dot net services presentation.
CQRS with dot net services presentation.CQRS with dot net services presentation.
CQRS with dot net services presentation.
 

Recently uploaded

A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 

Recently uploaded (20)

A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 

Scala Functions & Closures: Learn about methods, local functions, function literals, closures and more

  • 1. Scala Functions & Closures Neelkanth Sachdeva Consultant / Software Engineer Knoldus Software LLP , New Delhi neelkanthsachdeva.wordpress.com neelkanth@knoldus.com
  • 2. Methods The most common way to define a function is as a member of some object.Such a function is called a Method.
  • 3. /* * Normal Functions */ object LongLines extends App{ def ProcessFile(fileName: String, width: Int) { val source = Source.fromFile(fileName) for (line <- source.getLines) processLine(fileName, width, line) } private def processLine(filename: String, width: Int, line: String) { if (line.length > width) println(filename + ": " + line) } }
  • 4. Local functions Programs should be decomposed into many small functions that each do a well-defined task. One problem with this approach is that all the helper function names can pollute the program name space In Java → 1.Defining private methods. In Scala → 1. Defining private methods also works + 2. You can define functions inside other functions
  • 5. /* * Defining Local Functions More Easily */ object LongLines extends App { def ProcessFile(fileName: String,width: Int) { def processLine(line: String) { if (line.length > width) println(fileName + ": " + line) } val source = Source.fromFile(fileName) for (line <- source.getLines) processLine(line) } }
  • 6. First-class functions Scala has first-class functions. Not only can you define functions and call them, but you can write down functions as unnamed literals and then pass them around as values.
  • 7.
  • 8. Function Literals A function literal is compiled into a class that when instantiated at runtime is a function value. Then What is the difference ? Thus the distinction between function literals and values is that function literals exist in the source code, whereas function values exist as objects at runtime.
  • 9. Example: Simple function literal :- (x: Int) => x + 1 The => designates that this function converts the thing on the left (any integer x) to the thing on the right (x + 1). So, this is a function mapping any integer x to x + 1.
  • 10. Function values are objects, so → you can store them in variables scala> var increase = (x: Int) => x + 1 increase: (Int) => Int = <function> They are functions too , so → you can invoke them using the usual parentheses function-call notation. scala> increase(10) res0: Int = 11
  • 11. We've seen the nuts and bolts of function literals and function values. Many Scala libraries give you opportunities to use them e.g foreach method: scala> val someNumbers = List(-11, -10, -5, 0, 5, 10) someNumbers: List[Int] = List(-11, -10, -5, 0, 5, 10) scala> someNumbers.foreach((x: Int) => println(x)) filter method: scala> someNumbers.filter((x: Int) => x > 0)
  • 12. Short forms of function literals Scala provides a number of ways to leave out redundant information and write function literals more briefly. Keep your eyes open for these opportunities, because they allow you to remove clutter from your code. One way to make a function literal more brief is to leave off the parameter types. Thus, the previous example with filter could be written like this: scala> someNumbers.filter((x) => x > 0) res7: List[Int] = List(5, 10) Even leave the parentheses around x scala> someNumbers.filter( x => x > 0) res7: List[Int] = List(5, 10)
  • 13. Placeholder syntax 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. scala> someNumbers.filter( _ > 0) res9: List[Int] = List(5, 10)
  • 14. Partially applied functions someNumbers.foreach( println _ ) Scala treats this short form exactly as if you had written the following: someNumbers.foreach(x => println(x)) When you use an underscore in this way, you are writing a partially applied function.
  • 15. Examples: scala> def sum(a: Int, b: Int, c: Int) = a + b + c sum: (Int,Int,Int)Int scala> sum(1, 2, 3) res0: Int = 6 scala> val a = sum _ a: (Int, Int, Int) => Int = <function> scala> a.apply(1, 2, 3) res1: Int = 6
  • 16. scala> val b = sum(1, _: Int, 3) b: (Int) => Int = <function> scala> b(2) res15: Int = 6 In this case, b.apply invoked sum(1, 2, 3). scala> val c = sum <console>:5: error: missing arguments for method sum... follow this method with `_' if you want to treat it as a partially applied function val c = sum ˆ
  • 18. x → by contrast, is a bound variable, because it does have a meaning in the context of the function: it is defined as the function’s lone parameter, an Int. more → more is a free variable, because the Function literal does not itself give a meaning to it.
  • 19.
  • 20. So the closures is : The function value (the object) that’s created at runtime from this function literal is called a closure.
  • 21. (x: Int) => x + 1, is called a closed term, Thus a function value created at runtime from this function literal is not a closure in the strictest Sense . (x: Int) => x + more, is an open term. Therefore, any function value created at runtime from (x: Int) => x + more will by definition require that a binding for its free variable, more, be captured. The resulting function value, which will contain a reference to the captured more variable, is called a closure,
  • 22. 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.
  • 23.