Functions & closures


Published on

Function and Closures in Scala

Published in: Technology, Education
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Functions & closures

  1. 1. Scala Functions & ClosuresNeelkanth SachdevaConsultant / Software EngineerKnoldus Software LLP , New
  2. 2. MethodsThe most common way to define a function isas a member of some object.Such a function iscalled a Method.
  3. 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. 4. Local functionsPrograms should be decomposed into many small functions that eachdo a well-defined task. One problem with this approach is that all thehelper function names can pollute the program name spaceIn Java →1.Defining private methods.In Scala →1. Defining private methods also works +2. You can define functions inside other functions
  5. 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. 6. First-class functionsScala has first-class functions. Not only can youdefine functions and call them, but you can writedown functions as unnamed literals and thenpass them around as values.
  7. 7. Function LiteralsA function literal is compiled into a class thatwhen instantiated at runtime is a function value.Then What is the difference ?Thus the distinction between function literals andvalues is that function literals exist in the sourcecode, whereas function values exist as objects atruntime.
  8. 8. Example:Simple function literal :- (x: Int) => x + 1The => designates that this function converts the thing on the left (anyinteger x) to the thing on the right (x + 1). So, this is a function mappingany integer x to x + 1.
  9. 9. 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
  10. 10. Weve seen the nuts and bolts of function literals and functionvalues. Many Scala libraries give you opportunities to usethem e.gforeach 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)
  11. 11. Short forms of function literalsScala provides a number of ways to leave out redundant information andwrite function literals more briefly. Keep your eyes open for theseopportunities, because they allow you to remove clutter from your code.One way to make a function literal more brief is to leave off the parametertypes. 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 xscala> someNumbers.filter( x => x > 0)res7: List[Int] = List(5, 10)
  12. 12. Placeholder syntaxTo make a function literal even more concise, youcan use underscores as placeholders for one ormore parameters, so long as each parameterappears only one time within the function literal.scala> someNumbers.filter( _ > 0)res9: List[Int] = List(5, 10)
  13. 13. Partially applied functionssomeNumbers.foreach( println _ )Scala treats this short form exactly as if you hadwritten the following:someNumbers.foreach(x => println(x))When you use an underscore in this way, you arewriting a partially applied function.
  14. 14. Examples:scala> def sum(a: Int, b: Int, c: Int) = a + b + csum: (Int,Int,Int)Intscala> sum(1, 2, 3)res0: Int = 6scala> val a = sum _a: (Int, Int, Int) => Int = <function>scala> a.apply(1, 2, 3)res1: Int = 6
  15. 15. scala> val b = sum(1, _: Int, 3)b: (Int) => Int = <function>scala> b(2)res15: Int = 6In 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 asa partially applied functionval c = sum ˆ
  16. 16. Closures
  17. 17. x → by contrast, is a bound variable, because itdoes have a meaning in the context of thefunction: it is defined as the function’s loneparameter, an Int.more → more is a free variable, because theFunction literal does not itself give a meaning to it.
  18. 18. So the closures is :The function value (the object) that’s created atruntime from this function literal is called aclosure.
  19. 19. (x: Int) => x + 1, is called a closed term,Thus a function value created at runtime fromthis function literal is not a closure in the strictestSense .(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 freevariable, more, be captured. The resulting function value,which will contain a reference to the captured more variable,is called a closure,
  20. 20. Repeated ParametersScala allows you to indicate that the lastparameter to a function may be repeated. Thisallows clients to pass variable length argumentlists to the function.
  21. 21. Thank You