18
Scala Functions Short link to this slides http://bit.ly/s-scala-functions

Scala functions

Embed Size (px)

Citation preview

Page 1: Scala functions

Scala Functions Short link to this slides

http://bit.ly/s-scala-functions

Page 2: Scala functions

Things we will cover:1. Functions as methods on objects2. Local or nested functions vs private methods3. Function literals and function values4. Placeholder syntax5. Partial functions, partially applied functions & currying6. Tail recursive functions7. Function parameters types - repeated, named & default8. Function closure9. Functions vs methods - signature, type params & in-

depth.

Page 3: Scala functions

Functions as methods on objects

Page 4: Scala functions

Local or nested functions

Page 5: Scala functions

Function literals and function values

Page 6: Scala functions

Placeholder syntax for function parameters

Page 7: Scala functions

Partial function

Page 8: Scala functions

Partially applied functions

Page 9: Scala functions

Currying

Page 10: Scala functions

Tail recursive functions

Tail Recursion

Recursion

Tail recursive functions are functions that call themselves as their last action. Scala compiler will do tail call optimizations by not allocating a stack frame per function invocation and it would replace it with the function call to jump back to the beginning of the function after updating the function parameters with new values.

Page 11: Scala functions

Function parameter types

Page 12: Scala functions

Function closureThe name “closure” arises from the act of “closing” the function literal by “capturing” the bindings of its free variables.

A free variable is variable which the function literal does not define or is not passed into a function.

Take a look at e.g. on the side, abc is a free variable which is closed into incAbc function definition.

Closure sees the change to the variable every time a function invocation is done.

Page 13: Scala functions

Function vs methods - signature

Page 14: Scala functions

Function vs methods - type params

Page 15: Scala functions

Function vs methods - in depthA function is simply an object that wraps a method, viz. apply, and Scala provides convenience syntax for invoking the apply method of a function without having to actually name it.

scalac test.scala

Page 16: Scala functions

1

2

3

4

0

Page 17: Scala functions
Page 18: Scala functions

Slides - http://bit.ly/s-scala-functions

Thank you.