SlideShare a Scribd company logo
Functions In ScalaFunctions In Scala
Satendra Kumar
Software Consultant
Knoldus Software LLP
Satendra Kumar
Software Consultant
Knoldus Software LLP
Topics CoveredTopics Covered
Function
Function Literal
Higher Order Function
Partial Function
Partial Applied Function
Nested Function
Closures
Function
Function Literal
Higher Order Function
Partial Function
Partial Applied Function
Nested Function
Closures
FunctionFunction
A function is a type of procedure or routine. Which takes the input and return
a value.
function define like:
def square(x: Int): Int = { x * x }
* Function always return a single value.
Function LiteralFunction Literal
Function literal a function with no name in Scala source code, specified with function literal
syntax.
For example:
(x: Int, y: Int) => x + y
Anonymous function Another name for function literal.
Function LiteralFunction Literal
Function literal a function with no name in Scala source code, specified with function literal
syntax.
For example:
(x: Int, y: Int) => x + y
Anonymous function Another name for function literal.
A function literal is compiled into a class that when instantiated at runtime is a function value.
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. The distinction is much like
that between classes (source code) and objects (runtime).
Function LiteralFunction Literal
val fun2=(x: Int, y: Int) => x + y
val fun3 = (x: Int, y: Int, z: Int) => x + y + z
Higher Order Function
def filter(p: (A) Boolean): List[A]⇒
def map[B](f: (A) ⇒ B): List[B]
def foreach(f: (A) Unit): Unit⇒
Higher-order functions are functions that can either take other functions as arguments
or return them as results.
Higher order functions:
def collect[B](pf: PartialFunction[A, B]): List[B]
def calFun(operator: String): (Int, Int) => Int
Higher Order Function
(1 to 100).filter { (number:Int) => number % 2 == 0 }
Higher Order Function
(1 to 100).toList.filter { (number:Int) => number % 2 == 0 }
Or
(1 to 100).toList.filter { number => number % 2 == 0 }
Higher Order Function
(1 to 100).toList.filter { (number:Int) => number % 2 == 0 }
Or
(1 to 100).toList.filter { number => number % 2 == 0 }
Or
(1 to 100).toList.filter { _ % 2 == 0 }
Higher Order Function
def calFun(operator: String): (Int, Int) => Int = {
(a: Int, b: Int) =>
operator match {
case "+" => a + b
case "-" => a - b
case "*" => a * b
case "/" => a / b
}
}
Partial Function
A partial function is a function that is not defined for all possible arguments of the specified
type.
In Scala :
A partial function of type PartialFunction[A, B] is a unary function where the domain does not
necessarily include all values of type A.
The function isDefinedAt allows to test dynamically if a value is in the domain of the function.
val isEven: PartialFunction[Int, String] = {
case x if x % 2 == 0 => x + " is even"
}
Partial Function And Function
Partial Function:
val isEven: PartialFunction[Int, String] = {
case x if x % 2 == 0 => x + " is even"
}
Function:
def isEven(x: Int): String = {
require(x % 2 == 0)
x + " is even"
}
Both are doing same thing so what is difference between Function
and Partial Function ?
Diff B/W Partial Function And Function
The main distinction between PartialFunction and Function is that the user of a
PartialFunction may choose to do something different with input that is declared to be
outside its domain.
For example:
val sample = 1 to 10
val isEven: PartialFunction[Int, String] = {
case x if x % 2 == 0 => x + " is even"
}
// the method collect can use isDefinedAt to select which members to
collect
val evenNumbers = sample collect isEven
val isOdd: PartialFunction[Int, String] = {
case x if x % 2 == 1 => x + " is odd"
}
// the method orElse allows chaining another partial function to handle
// input outside the declared domain
val numbers = sample map (isEven orElse isOdd)
match
def checkNumber(a: Int):String = a match {
case x if x % 2 == 0 => x + " is even"
case x if x % 2 == 1 => x + " is odd"
case _ => "Neither even nor odd"
}
match is method or keyword ?
match
def checkNumber(a: Int):String = a match {
case x if x % 2 == 0 => x + " is even"
case x if x % 2 == 1 => x + " is odd"
case _ => "Neither even nor odd"
}
match is method or keyword ?
Answer => Keyword
match
def checkNumber(a: Int):String = a match {
case x if x % 2 == 0 => x + " is even"
case x if x % 2 == 1 => x + " is odd"
case _ => "Neither even nor odd"
}
match is method or keyword ?
Answer => Keyword
Why keyword ?
Why match is keyword ?
From: David Pollak <dpp <at> athena.com>
Subject: match question
Newsgroups: gmane.comp.lang.scala.debate
Date: 2008-01-21 20:30:29 GMT (6 years, 49 weeks, 5 days, 3 hours and 8 minutes ago)
Folks,
Why is 'match' a language level construct rather than a method on Any?
Wouldn't "def match[XX](func: PartialFunction[this.type, XX]): XX = ..."
result in syntactically identical code?
Thanks,
David
Why match is keyword ?
From: martin odersky <martin.odersky <at> epfl.ch>
Subject: Re: match question
Newsgroups: gmane.comp.lang.scala.debate
Date: 2008-01-21 21:25:02 GMT (6 years, 49 weeks, 5 days, 2 hours and 27 minutes ago)
On Jan 21, 2008 9:35 PM, Erik Engbrecht <erik.engbrecht <at> gmail.com> wrote:
> I always wondered that...
>
> Good question.
>
> On 1/21/08, David Pollak <dpp <at> athena.com> wrote:
> > Folks,
> >
> > Why is 'match' a language level construct rather than a method on Any?
> >
> > Wouldn't "def match[XX](func: PartialFunction[ this.type, XX]): XX = ..."
> > result in syntactically identical code?
> >
It used to be that way in Scala 1. I am no longer sure why we changed.
syntax highlighting? error reporting? not sure. I don't think it
matters much either way, though.
Cheers -- Martin
Partial Applied Function
When you invoke a function, If you send only a few arguments, then you get back a partially
applied function. This gives you the convenience of binding some arguments and leaving the
rest to be filled in later.
Example: uncurried version
scala> def sum(a:Int,b:Int,c:Int,d:Int):Int=a+b+c+d
sum: (a: Int, b: Int, c: Int, d: Int)Int
scala> val partialAppliedFun=sum(1,2,_:Int,_:Int)
partialAppliedFun: (Int, Int) => Int = <function2>
scala> partialAppliedFun(3,4)
res46: Int = 10
Example: curried version
scala> def sum(a:Int,b:Int)(c:Int)(d:Int):Int=a+b+c+d
sum: (a: Int, b: Int)(c: Int)(d: Int)Int
scala> val partialAppliedFun=sum(1,2) _
partialAppliedFun: Int => (Int => Int) = <function1>
scala> partialAppliedFun(3)(4)
res47: Int = 10
Uncurried Function Vs Curried Function
By Martin Odersky
Currying is mostly used if the second parameter section is a function or a by name parameter.
This has two advantages.
First, the function argument can then look like a code block enclosed in braces.
E.g.
using(new File(name)) { f =>
...
}
This reads better than the uncurried alternative:
using(new File(name), f => {
...
})
Uncurried Function Vs Curried Function
Second, and more importantly, type inference can usually figure out the function's parameter
type, so it does not have to be given at the call site.
For instance, if I define a max function over lists like this:
def max[T](xs: List[T])(compare: (T, T) => Boolean)
I can call it like this:
max(List(1, -3, 43, 0)) ((x, y) => x < y)
or even shorter:
max(List(1, -3, 43, 0)) (_ < _)
If I defined max as an uncurried function, this would not work, I'd have to
call it like this:
max(List(1, -3, 43, 0), (x: Int, y: Int) => x < y)
If the last parameter is not a function or by-name parameter, I would
not advise currying. Scala's _ notatation is amost as lightweight,
more flexible, and IMO clearer.
Nested Function
A nested function is a function defined inside another function.
Purpose:
Nested functions are used as helper functions or as recursive functions inside another
function. This has the structural benefit of organizing the code, avoids polluting the scope,
and also allows functions to share state easily.
As nested function can access local variables of the enclosing function, sharing of state is
possible without passing parameters to the nested function or use a global variable,
simplifying code.
Also called Local function.
Nested Function
def processFile(filename: String, width: Int) {
def processLine(filename: String, width: Int, line: String) {
if (line.length > width)
println(filename + ": " + line)
}
val source = Source.fromFile(filename)
for (line <- source.getLines()) {
processLine(filename, width, line)
}
}
Nested Function
def processFile(filename: String, width: Int) {
def processLine(filename: String, width: Int, line: String) {
if (line.length > width)
println(filename + ": " + line)
}
val source = Source.fromFile(filename)
for (line <- source.getLines()) {
processLine(filename, width, line)
}
}
possible improvement ?
Nested Function
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)
}
Closures
scala> var more = 1
more: Int = 1
scala> val addMore = (x: Int) => x + more
addMore: Int => Int = <function1>
scala> addMore(10)
res6: Int = 11
The function value (the object) that’s created at runtime from this function literal is called a
closure.
The name arises from the act of “closing” the function literal by “capturing” the bindings of its free
variables.
A function literal with no free variables, such as (x: Int) => x + 1 , is called a closed term,
where a term is a bit of source code.Thus a function value created at run-time from this function
literal is not a closure in the strictest sense, because (x: Int) => x + 1 is already closed as written.
Closures mean that you can save some data inside a function that's only accessible to a
specific returning function, i.e the returning function keeps its execution environment.
Closures
scala> var more = 1
more: Int = 1
scala> val addMore = (x: Int) => x + more
addMore: Int => Int = <function1>
scala> addMore(10)
res6: Int = 11
scala> more=10
more: Int = 10
scala> addMore(10)
What is output ?
Closures
scala> var more = 1
more: Int = 1
scala> val addMore = (x: Int) => x + more
addMore: Int => Int = <function1>
scala> addMore(10)
res6: Int = 11
scala> more=10
more: Int = 10
scala> addMore(10)
res7: Int = 20
Closures
scala> def makeIncreaser(more: Int) = (x: Int) => x + more
makeIncreaser: (more: Int)Int => Int
scala> val inc1 = makeIncreaser(1)
inc1: Int => Int = <function1>
scala> val inc9999 = makeIncreaser(9999)
inc9999: Int => Int = <function1>
scala> inc1(10) output ?
scala> inc9999(10) output ?
Closures
scala> def makeIncreaser(more: Int) = (x: Int) => x + more
makeIncreaser: (more: Int)Int => Int
scala> val inc1 = makeIncreaser(1)
inc1: Int => Int = <function1>
scala> val inc9999 = makeIncreaser(9999)
inc9999: Int => Int = <function1>
scala> inc1(10)
res8: Int = 11
scala> inc9999(10)
res9: Int = 10009
Reason : the variable instance used is the one that was active at the time the closure was
created.
Question And Option[Answer]Question And Option[Answer]
ThanksThanks

More Related Content

ODP
Effective way to code in Scala
ODP
Type Parameterization
PPT
Scala collection
ODP
Collections In Scala
PDF
Scala collections
PDF
Scala collections api expressivity and brevity upgrade from java
PPTX
Scala for curious
PDF
Python data handling notes
Effective way to code in Scala
Type Parameterization
Scala collection
Collections In Scala
Scala collections
Scala collections api expressivity and brevity upgrade from java
Scala for curious
Python data handling notes

What's hot (20)

PDF
PDF
Scala Paradigms
PPTX
Scala Back to Basics: Type Classes
PDF
Sequence and Traverse - Part 3
PPT
JBUG 11 - Scala For Java Programmers
PDF
Monad Transformers - Part 1
PDF
Functors
PDF
Monoids - Part 1 - with examples using Scalaz and Cats
PDF
Data Structures In Scala
PDF
Pragmatic Real-World Scala (short version)
PDF
Demystifying functional programming with Scala
PDF
Fp in scala part 2
PDF
Scala parallel-collections
ODP
Functional Programming With Scala
PPTX
Joy of scala
PDF
Arrays In Python | Python Array Operations | Edureka
PDF
One Monad to Rule Them All
PDF
Functional Programming by Examples using Haskell
PDF
Reasoning about laziness
PDF
Learning Functional Programming Without Growing a Neckbeard
Scala Paradigms
Scala Back to Basics: Type Classes
Sequence and Traverse - Part 3
JBUG 11 - Scala For Java Programmers
Monad Transformers - Part 1
Functors
Monoids - Part 1 - with examples using Scalaz and Cats
Data Structures In Scala
Pragmatic Real-World Scala (short version)
Demystifying functional programming with Scala
Fp in scala part 2
Scala parallel-collections
Functional Programming With Scala
Joy of scala
Arrays In Python | Python Array Operations | Edureka
One Monad to Rule Them All
Functional Programming by Examples using Haskell
Reasoning about laziness
Learning Functional Programming Without Growing a Neckbeard
Ad

Similar to Functions In Scala (20)

PPT
Scala functions
PDF
Scala qq
ODP
Functions & Closures in Scala
ODP
Functions & Closures in Scala
ODP
Functions & closures
ODP
Scala oo (1)
ODP
Functional Objects & Function and Closures
ODP
Functional Objects & Function and Closures
ODP
Functional Objects & Function and Closures
PPTX
Principles of functional progrmming in scala
PPTX
Functional Programming Concepts for Imperative Programmers
PDF
Lecture 3
KEY
Functional programming in clojure
PDF
Scala: A brief tutorial
PPTX
Functional programming
PDF
Introductiontoprogramminginscala
PPTX
Столпы функционального программирования для адептов ООП, Николай Мозговой
PDF
Functional programming ii
PPTX
Scala Introduction - Synerzip
PPTX
Introduction to Scala
Scala functions
Scala qq
Functions & Closures in Scala
Functions & Closures in Scala
Functions & closures
Scala oo (1)
Functional Objects & Function and Closures
Functional Objects & Function and Closures
Functional Objects & Function and Closures
Principles of functional progrmming in scala
Functional Programming Concepts for Imperative Programmers
Lecture 3
Functional programming in clojure
Scala: A brief tutorial
Functional programming
Introductiontoprogramminginscala
Столпы функционального программирования для адептов ООП, Николай Мозговой
Functional programming ii
Scala Introduction - Synerzip
Introduction to Scala
Ad

More from Knoldus Inc. (20)

PPTX
Angular Hydration Presentation (FrontEnd)
PPTX
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
PPTX
Self-Healing Test Automation Framework - Healenium
PPTX
Kanban Metrics Presentation (Project Management)
PPTX
Java 17 features and implementation.pptx
PPTX
Chaos Mesh Introducing Chaos in Kubernetes
PPTX
GraalVM - A Step Ahead of JVM Presentation
PPTX
Nomad by HashiCorp Presentation (DevOps)
PPTX
Nomad by HashiCorp Presentation (DevOps)
PPTX
DAPR - Distributed Application Runtime Presentation
PPTX
Introduction to Azure Virtual WAN Presentation
PPTX
Introduction to Argo Rollouts Presentation
PPTX
Intro to Azure Container App Presentation
PPTX
Insights Unveiled Test Reporting and Observability Excellence
PPTX
Introduction to Splunk Presentation (DevOps)
PPTX
Code Camp - Data Profiling and Quality Analysis Framework
PPTX
AWS: Messaging Services in AWS Presentation
PPTX
Amazon Cognito: A Primer on Authentication and Authorization
PPTX
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
PPTX
Managing State & HTTP Requests In Ionic.
Angular Hydration Presentation (FrontEnd)
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Self-Healing Test Automation Framework - Healenium
Kanban Metrics Presentation (Project Management)
Java 17 features and implementation.pptx
Chaos Mesh Introducing Chaos in Kubernetes
GraalVM - A Step Ahead of JVM Presentation
Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)
DAPR - Distributed Application Runtime Presentation
Introduction to Azure Virtual WAN Presentation
Introduction to Argo Rollouts Presentation
Intro to Azure Container App Presentation
Insights Unveiled Test Reporting and Observability Excellence
Introduction to Splunk Presentation (DevOps)
Code Camp - Data Profiling and Quality Analysis Framework
AWS: Messaging Services in AWS Presentation
Amazon Cognito: A Primer on Authentication and Authorization
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
Managing State & HTTP Requests In Ionic.

Functions In Scala

  • 1. Functions In ScalaFunctions In Scala Satendra Kumar Software Consultant Knoldus Software LLP Satendra Kumar Software Consultant Knoldus Software LLP
  • 2. Topics CoveredTopics Covered Function Function Literal Higher Order Function Partial Function Partial Applied Function Nested Function Closures Function Function Literal Higher Order Function Partial Function Partial Applied Function Nested Function Closures
  • 3. FunctionFunction A function is a type of procedure or routine. Which takes the input and return a value. function define like: def square(x: Int): Int = { x * x } * Function always return a single value.
  • 4. Function LiteralFunction Literal Function literal a function with no name in Scala source code, specified with function literal syntax. For example: (x: Int, y: Int) => x + y Anonymous function Another name for function literal.
  • 5. Function LiteralFunction Literal Function literal a function with no name in Scala source code, specified with function literal syntax. For example: (x: Int, y: Int) => x + y Anonymous function Another name for function literal. A function literal is compiled into a class that when instantiated at runtime is a function value. 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. The distinction is much like that between classes (source code) and objects (runtime).
  • 6. Function LiteralFunction Literal val fun2=(x: Int, y: Int) => x + y val fun3 = (x: Int, y: Int, z: Int) => x + y + z
  • 7. Higher Order Function def filter(p: (A) Boolean): List[A]⇒ def map[B](f: (A) ⇒ B): List[B] def foreach(f: (A) Unit): Unit⇒ Higher-order functions are functions that can either take other functions as arguments or return them as results. Higher order functions: def collect[B](pf: PartialFunction[A, B]): List[B] def calFun(operator: String): (Int, Int) => Int
  • 8. Higher Order Function (1 to 100).filter { (number:Int) => number % 2 == 0 }
  • 9. Higher Order Function (1 to 100).toList.filter { (number:Int) => number % 2 == 0 } Or (1 to 100).toList.filter { number => number % 2 == 0 }
  • 10. Higher Order Function (1 to 100).toList.filter { (number:Int) => number % 2 == 0 } Or (1 to 100).toList.filter { number => number % 2 == 0 } Or (1 to 100).toList.filter { _ % 2 == 0 }
  • 11. Higher Order Function def calFun(operator: String): (Int, Int) => Int = { (a: Int, b: Int) => operator match { case "+" => a + b case "-" => a - b case "*" => a * b case "/" => a / b } }
  • 12. Partial Function A partial function is a function that is not defined for all possible arguments of the specified type. In Scala : A partial function of type PartialFunction[A, B] is a unary function where the domain does not necessarily include all values of type A. The function isDefinedAt allows to test dynamically if a value is in the domain of the function. val isEven: PartialFunction[Int, String] = { case x if x % 2 == 0 => x + " is even" }
  • 13. Partial Function And Function Partial Function: val isEven: PartialFunction[Int, String] = { case x if x % 2 == 0 => x + " is even" } Function: def isEven(x: Int): String = { require(x % 2 == 0) x + " is even" } Both are doing same thing so what is difference between Function and Partial Function ?
  • 14. Diff B/W Partial Function And Function The main distinction between PartialFunction and Function is that the user of a PartialFunction may choose to do something different with input that is declared to be outside its domain. For example: val sample = 1 to 10 val isEven: PartialFunction[Int, String] = { case x if x % 2 == 0 => x + " is even" } // the method collect can use isDefinedAt to select which members to collect val evenNumbers = sample collect isEven val isOdd: PartialFunction[Int, String] = { case x if x % 2 == 1 => x + " is odd" } // the method orElse allows chaining another partial function to handle // input outside the declared domain val numbers = sample map (isEven orElse isOdd)
  • 15. match def checkNumber(a: Int):String = a match { case x if x % 2 == 0 => x + " is even" case x if x % 2 == 1 => x + " is odd" case _ => "Neither even nor odd" } match is method or keyword ?
  • 16. match def checkNumber(a: Int):String = a match { case x if x % 2 == 0 => x + " is even" case x if x % 2 == 1 => x + " is odd" case _ => "Neither even nor odd" } match is method or keyword ? Answer => Keyword
  • 17. match def checkNumber(a: Int):String = a match { case x if x % 2 == 0 => x + " is even" case x if x % 2 == 1 => x + " is odd" case _ => "Neither even nor odd" } match is method or keyword ? Answer => Keyword Why keyword ?
  • 18. Why match is keyword ? From: David Pollak <dpp <at> athena.com> Subject: match question Newsgroups: gmane.comp.lang.scala.debate Date: 2008-01-21 20:30:29 GMT (6 years, 49 weeks, 5 days, 3 hours and 8 minutes ago) Folks, Why is 'match' a language level construct rather than a method on Any? Wouldn't "def match[XX](func: PartialFunction[this.type, XX]): XX = ..." result in syntactically identical code? Thanks, David
  • 19. Why match is keyword ? From: martin odersky <martin.odersky <at> epfl.ch> Subject: Re: match question Newsgroups: gmane.comp.lang.scala.debate Date: 2008-01-21 21:25:02 GMT (6 years, 49 weeks, 5 days, 2 hours and 27 minutes ago) On Jan 21, 2008 9:35 PM, Erik Engbrecht <erik.engbrecht <at> gmail.com> wrote: > I always wondered that... > > Good question. > > On 1/21/08, David Pollak <dpp <at> athena.com> wrote: > > Folks, > > > > Why is 'match' a language level construct rather than a method on Any? > > > > Wouldn't "def match[XX](func: PartialFunction[ this.type, XX]): XX = ..." > > result in syntactically identical code? > > It used to be that way in Scala 1. I am no longer sure why we changed. syntax highlighting? error reporting? not sure. I don't think it matters much either way, though. Cheers -- Martin
  • 20. Partial Applied Function When you invoke a function, If you send only a few arguments, then you get back a partially applied function. This gives you the convenience of binding some arguments and leaving the rest to be filled in later. Example: uncurried version scala> def sum(a:Int,b:Int,c:Int,d:Int):Int=a+b+c+d sum: (a: Int, b: Int, c: Int, d: Int)Int scala> val partialAppliedFun=sum(1,2,_:Int,_:Int) partialAppliedFun: (Int, Int) => Int = <function2> scala> partialAppliedFun(3,4) res46: Int = 10 Example: curried version scala> def sum(a:Int,b:Int)(c:Int)(d:Int):Int=a+b+c+d sum: (a: Int, b: Int)(c: Int)(d: Int)Int scala> val partialAppliedFun=sum(1,2) _ partialAppliedFun: Int => (Int => Int) = <function1> scala> partialAppliedFun(3)(4) res47: Int = 10
  • 21. Uncurried Function Vs Curried Function By Martin Odersky Currying is mostly used if the second parameter section is a function or a by name parameter. This has two advantages. First, the function argument can then look like a code block enclosed in braces. E.g. using(new File(name)) { f => ... } This reads better than the uncurried alternative: using(new File(name), f => { ... })
  • 22. Uncurried Function Vs Curried Function Second, and more importantly, type inference can usually figure out the function's parameter type, so it does not have to be given at the call site. For instance, if I define a max function over lists like this: def max[T](xs: List[T])(compare: (T, T) => Boolean) I can call it like this: max(List(1, -3, 43, 0)) ((x, y) => x < y) or even shorter: max(List(1, -3, 43, 0)) (_ < _) If I defined max as an uncurried function, this would not work, I'd have to call it like this: max(List(1, -3, 43, 0), (x: Int, y: Int) => x < y) If the last parameter is not a function or by-name parameter, I would not advise currying. Scala's _ notatation is amost as lightweight, more flexible, and IMO clearer.
  • 23. Nested Function A nested function is a function defined inside another function. Purpose: Nested functions are used as helper functions or as recursive functions inside another function. This has the structural benefit of organizing the code, avoids polluting the scope, and also allows functions to share state easily. As nested function can access local variables of the enclosing function, sharing of state is possible without passing parameters to the nested function or use a global variable, simplifying code. Also called Local function.
  • 24. Nested Function def processFile(filename: String, width: Int) { def processLine(filename: String, width: Int, line: String) { if (line.length > width) println(filename + ": " + line) } val source = Source.fromFile(filename) for (line <- source.getLines()) { processLine(filename, width, line) } }
  • 25. Nested Function def processFile(filename: String, width: Int) { def processLine(filename: String, width: Int, line: String) { if (line.length > width) println(filename + ": " + line) } val source = Source.fromFile(filename) for (line <- source.getLines()) { processLine(filename, width, line) } } possible improvement ?
  • 26. Nested Function 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) }
  • 27. Closures scala> var more = 1 more: Int = 1 scala> val addMore = (x: Int) => x + more addMore: Int => Int = <function1> scala> addMore(10) res6: Int = 11 The function value (the object) that’s created at runtime from this function literal is called a closure. The name arises from the act of “closing” the function literal by “capturing” the bindings of its free variables. A function literal with no free variables, such as (x: Int) => x + 1 , is called a closed term, where a term is a bit of source code.Thus a function value created at run-time from this function literal is not a closure in the strictest sense, because (x: Int) => x + 1 is already closed as written. Closures mean that you can save some data inside a function that's only accessible to a specific returning function, i.e the returning function keeps its execution environment.
  • 28. Closures scala> var more = 1 more: Int = 1 scala> val addMore = (x: Int) => x + more addMore: Int => Int = <function1> scala> addMore(10) res6: Int = 11 scala> more=10 more: Int = 10 scala> addMore(10) What is output ?
  • 29. Closures scala> var more = 1 more: Int = 1 scala> val addMore = (x: Int) => x + more addMore: Int => Int = <function1> scala> addMore(10) res6: Int = 11 scala> more=10 more: Int = 10 scala> addMore(10) res7: Int = 20
  • 30. Closures scala> def makeIncreaser(more: Int) = (x: Int) => x + more makeIncreaser: (more: Int)Int => Int scala> val inc1 = makeIncreaser(1) inc1: Int => Int = <function1> scala> val inc9999 = makeIncreaser(9999) inc9999: Int => Int = <function1> scala> inc1(10) output ? scala> inc9999(10) output ?
  • 31. Closures scala> def makeIncreaser(more: Int) = (x: Int) => x + more makeIncreaser: (more: Int)Int => Int scala> val inc1 = makeIncreaser(1) inc1: Int => Int = <function1> scala> val inc9999 = makeIncreaser(9999) inc9999: Int => Int = <function1> scala> inc1(10) res8: Int = 11 scala> inc9999(10) res9: Int = 10009 Reason : the variable instance used is the one that was active at the time the closure was created.