SlideShare a Scribd company logo
Functional programming in
Scala
https://github.com/ganeshayadiyala/functional-programming-in-scala
● Ganesha Yadiyala
● Big data consultant at
datamantra.io
● Consult in spark and scala
● ganeshayadiyala@gmail.com
Agenda
● Programming paradigms
● Functional Programming
● Advantages of FP
● History of Scala
● Basics of scala
● Functional Aspect of Scala
Programming Paradigms
Programming Paradigms
● Programming Paradigm is a approach to programming
● It will be based on set of principles or theory
● Different ways of thinking.
● Different types
○ Imperative
○ Functional
Imperative Programming
Imperative programming is a programming paradigm that uses
statements that change a program's state.
Example :
● C#
● C++
● Java
Functional Programming
A programming style that models computation as the evaluation of
expression.
Example:
● Haskell
● Erlang
● Lisp
● Clojure
Expression vs Statement
Expression : evaluated to produce a value without changing state.
Statement : executed to update state.
Example:
Expression -> val isEven = if(x%2 == 0) true else false
Example :
Statement -> boolean isEven = true
if(x%2 == 0)
isEven = true
else
isEven = false
Functional Programming
History of Functional Programming
● Mathematical abstraction Lambda Calculus was the foundation
for functional Programming
● Lambda calculus was developed in 1930s to be used for
functional definition, functional application and recursion.
● It states that any computation can be achieved by sending the
input to some black box, which produces its result.
● This black box is lambda functions, and in FP it’s functions.
● LISP was the first functional programming language. It was
defined by McCarthy in 1958
Imperative vs Functional Programming
Characteristics Imperative Functional
State changes Important Non-existent
Order of execution Important Low importance
Primary flow control
Loops, conditions and method
(function) calls
Function calls
Primary manipulation unit
Instances of structures or
classes
Functions
Characteristics of FP
● Immutable data
● Lazy evaluation
● No side effects
● Referential transparency
● Functions are first class citizens
Immutable data
Mutable Immutable
var collection = [1,2,3,4]
for ( i = 0; i<collection.length; i++) {
collection[i]+=1;
}
Uses loop for updating
collection is updated in place
val collection = [1,2,3,4]
val newCollection = collection.map(value
=> value +1)
Uses transformation for change
Creates a new copy of collection. Leaves
collection intact
Advantages of FP
● Better modularity
● Shorter code
● Increased developer productivity
● Less number of bugs
● Perfect for distributed computing because of immutability
● Easier debugging
Limitations of FP
● Real world programs have to do side effects
● Difficult to understand for the beginner
● Very difficult to debug the nature of lazy evaluation
● Memory intensive
History of Scala
Scala History
● Martin Odersky is the creator
● Curious about compilers from beginning
● Created first compiler in 1995 - Pizza
○ Generics,Function pointers, Case class and pattern matching
● Led to javac compiler and generics eventually
○ Java is a strict language and hard to implement these new ideas
Scala History cont..
● 1999 - Started working on a language
○ Combines Object orientation with functional programming
○ Created Funnel language
○ It was not a user friendly language
○ New languages with less libraries are hard to adopt
● In 2001, design for Scala started, released first in 2003
● Scala is not an extension of Java
● Scala translates into JAVA byte code
● One implementation of .Net compatible version, now out dated
Scala Philosophy
● Growable language
○ Embed new DSL/add new types
● Scalable language
○ Same concepts in small and large applications
● Deep rather than broad
○ Focus on abstraction and composition
Why scala
● Hybrid programming language
● Statically typed
● Runs on the jvm
● Can execute java code
Basics of Scala
Everything is an Object
● Supports object oriented programming
● Including primitive types, everything in scala is an object
Example:
● val x = 10
● x.toString()
Statically Typed Language
● var message = “hello”
● message = “bye”
● message = 100 //compilation error
● def abs(x:Int) : Int = { ??? }
● abs(“100”) //compilation error
Type Inference
● val employeeName : String = “Joy”
● val department = “HR” //Type inferred as String
● val age = 35 //Type inferred as Int
Collections
● List,Set,Map etc..
● Mutable
● Immutable
● Functional API
Example:
val integerList = List(1,2,3)
Functional Aspect of Scala
Operators are also a Function
For example
● val sum = 2 + 3
Is same as,
● val sum = 2.+(3) //because ‘+’ operator here is a function
Functions in Scala
● Higher order function
● Anonymous function
● Currying
● Tail recursion
Defining a Function in Scala
● Defining a function
In Scala -
def sum(x:Int,y:Int) : Int = x+y
In Java -
public int sum(int x,int y){
return x+y;
}
Assigning function to variable
Example :
def add = (x:Int,y:Int) => x+y
add(2,3) //should return 5
Higher Order Functions
Function that takes functions as a parameters or return function as
a result is called higher order functions
Example : com.ganesh.functions.HigherOrderFunctions.scala
Anonymous Function
Scala provides a relatively lightweight syntax for defining
anonymous functions.
Example:
(x: Int) => x + 1
Shorthand for above function is,
new Function1[Int, Int] {
def apply(x: Int): Int = x + 1
}
Currying
Currying allows to turn a function that expects two arguments into a
function that expects only one, and that function returns a function
that expects the second argument. Creating basically a chain of
functions.
Example : com.ganesh.functions.Currying.scala
Implicit Parameters
The final parameter list on a method can be marked implicit, which
means the values will be taken from the context in which they are
called.
● It means that if no value is supplied when called, the compiler
will look for an implicit value and pass it in for you.
● Implicits are useful in defining default implementations
available. When you need a custom implementation, you can
pass one in explicitly.
Example : com.ganesh.implicits.Implicits.scala
Tail Recursion
● Tail recursion is a special kind of recursion where the recursive
call is the very last thing in the function.
● tail-recursive function will only use a single stack frame as
opposed to hundreds or even thousands in case of normal
recursive function.
● Tail recursion is much faster because it executes using single
stack frame
Example : com.ganesh.functions.TailRecursion.scala
Transformation on Collections
We can perform different transformations on collection using
collection API.
Example:
com.ganesh.transformations.SimpleTransformations.scala
com.ganesh.transformations.AdvancedTransformations.scala
Error Handling
Scala does not have checked exceptions like Java, so you can't do
something like this to force a programmer to deal with an
exception.
Example :
com.ganesh.exceptionhandling.ExceptionThrowing.scala
com.ganesh.exceptionhandling.UsingOptions.scala
References
● https://www.coursera.org/learn/progfun1/ - Scala course by
Martin Odersky
● http://www.dipmat.unict.it/~barba/PROG-LANG/PROGRAMMI-
TESTI/READING-MATERIAL/ShortIntroFPprog-lang.htm -
Functional programming and lambda calculus
● Functional Programming in Scala

More Related Content

PPTX
Introduction to Scala
Mohammad Hossein Rimaz
 
PDF
Programación Funcional 101 con Scala y ZIO 2.0
Jorge Vásquez
 
PPT
Django, What is it, Why is it cool?
Tom Brander
 
PDF
Introduction to Apache Beam
Jean-Baptiste Onofré
 
PDF
Spark shuffle introduction
colorant
 
PDF
Introduction to Cassandra
Gokhan Atil
 
PPTX
Apache Spark Architecture
Alexey Grishchenko
 
PDF
Beyond SQL: Speeding up Spark with DataFrames
Databricks
 
Introduction to Scala
Mohammad Hossein Rimaz
 
Programación Funcional 101 con Scala y ZIO 2.0
Jorge Vásquez
 
Django, What is it, Why is it cool?
Tom Brander
 
Introduction to Apache Beam
Jean-Baptiste Onofré
 
Spark shuffle introduction
colorant
 
Introduction to Cassandra
Gokhan Atil
 
Apache Spark Architecture
Alexey Grishchenko
 
Beyond SQL: Speeding up Spark with DataFrames
Databricks
 

What's hot (20)

PPT
Hadoop Map Reduce
VNIT-ACM Student Chapter
 
PPTX
Virtual function in C++ Pure Virtual Function
Kamlesh Makvana
 
PPTX
Java Annotations
Serhii Kartashov
 
PDF
The Zen of High Performance Messaging with NATS
NATS
 
PPTX
Getting started with typescript
C...L, NESPRESSO, WAFAASSURANCE, SOFRECOM ORANGE
 
PPTX
PostgreSQL Database Slides
metsarin
 
PDF
Airflow introduction
Chandler Huang
 
PPTX
Gradle
Jadson Santos
 
PPTX
GIT presentation
Naim Latifi
 
PPTX
Design Pattern - Singleton Pattern
Mudasir Qazi
 
PPTX
Flink vs. Spark
Slim Baltagi
 
PPTX
Express JS Rest API Tutorial
Simplilearn
 
PDF
Alphorm.com Formation Ansible : Le Guide Complet du Débutant
Alphorm
 
PPTX
Introduction to Storm
Chandler Huang
 
PDF
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Edureka!
 
PPTX
.Net Core
Bertrand Le Roy
 
PDF
Scaling and Unifying SciKit Learn and Apache Spark Pipelines
Databricks
 
PPTX
Basics of MongoDB
HabileLabs
 
PDF
Efficient Kubernetes scaling using Karpenter
Marko Bevc
 
PDF
Top 5 Mistakes to Avoid When Writing Apache Spark Applications
Cloudera, Inc.
 
Hadoop Map Reduce
VNIT-ACM Student Chapter
 
Virtual function in C++ Pure Virtual Function
Kamlesh Makvana
 
Java Annotations
Serhii Kartashov
 
The Zen of High Performance Messaging with NATS
NATS
 
Getting started with typescript
C...L, NESPRESSO, WAFAASSURANCE, SOFRECOM ORANGE
 
PostgreSQL Database Slides
metsarin
 
Airflow introduction
Chandler Huang
 
GIT presentation
Naim Latifi
 
Design Pattern - Singleton Pattern
Mudasir Qazi
 
Flink vs. Spark
Slim Baltagi
 
Express JS Rest API Tutorial
Simplilearn
 
Alphorm.com Formation Ansible : Le Guide Complet du Débutant
Alphorm
 
Introduction to Storm
Chandler Huang
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Edureka!
 
.Net Core
Bertrand Le Roy
 
Scaling and Unifying SciKit Learn and Apache Spark Pipelines
Databricks
 
Basics of MongoDB
HabileLabs
 
Efficient Kubernetes scaling using Karpenter
Marko Bevc
 
Top 5 Mistakes to Avoid When Writing Apache Spark Applications
Cloudera, Inc.
 
Ad

Viewers also liked (20)

PDF
Interactive Data Analysis in Spark Streaming
datamantra
 
PDF
Real time ETL processing using Spark streaming
datamantra
 
PDF
Introduction to Spark 2.0 Dataset API
datamantra
 
PDF
Productionalizing a spark application
datamantra
 
PDF
Introduction to spark 2.0
datamantra
 
PDF
Building end to end streaming application on Spark
datamantra
 
PDF
Anatomy of spark catalyst
datamantra
 
PDF
Anatomy of Data Frame API : A deep dive into Spark Data Frame API
datamantra
 
PDF
Introduction to concurrent programming with akka actors
datamantra
 
PDF
Introduction to Structured Streaming
datamantra
 
PDF
Interactive workflow management using Azkaban
datamantra
 
PDF
Anatomy of Data Source API : A deep dive into Spark Data source API
datamantra
 
PDF
Building scalable rest service using Akka HTTP
datamantra
 
PDF
Introduction to Apache Spark
datamantra
 
PDF
Functional programming in Scala
Damian Jureczko
 
PDF
Introduction to Spark Internals
Pietro Michiardi
 
PPTX
Platform for Data Scientists
datamantra
 
PPTX
Telco analytics at scale
datamantra
 
PDF
Introduction to Spark Streaming
datamantra
 
PDF
Evolution of apache spark
datamantra
 
Interactive Data Analysis in Spark Streaming
datamantra
 
Real time ETL processing using Spark streaming
datamantra
 
Introduction to Spark 2.0 Dataset API
datamantra
 
Productionalizing a spark application
datamantra
 
Introduction to spark 2.0
datamantra
 
Building end to end streaming application on Spark
datamantra
 
Anatomy of spark catalyst
datamantra
 
Anatomy of Data Frame API : A deep dive into Spark Data Frame API
datamantra
 
Introduction to concurrent programming with akka actors
datamantra
 
Introduction to Structured Streaming
datamantra
 
Interactive workflow management using Azkaban
datamantra
 
Anatomy of Data Source API : A deep dive into Spark Data source API
datamantra
 
Building scalable rest service using Akka HTTP
datamantra
 
Introduction to Apache Spark
datamantra
 
Functional programming in Scala
Damian Jureczko
 
Introduction to Spark Internals
Pietro Michiardi
 
Platform for Data Scientists
datamantra
 
Telco analytics at scale
datamantra
 
Introduction to Spark Streaming
datamantra
 
Evolution of apache spark
datamantra
 
Ad

Similar to Functional programming in Scala (20)

PDF
Understanding Implicits in Scala
datamantra
 
PDF
Functional Programming in Ruby
Alex Teut
 
PPTX
Functional Programming in JavaScript & ESNext
Unfold UI
 
PDF
Python functional programming
Geison Goes
 
PDF
Yes scala can!
amirmoulavi
 
PDF
Ruby Functional Programming
Geison Goes
 
PDF
Introduction to functional programming
Konrad Szydlo
 
PPTX
Functional Programming.pptx
KarthickT28
 
PDF
Java 8
vilniusjug
 
PDF
(3) cpp procedural programming
Nico Ludwig
 
PDF
An Introduction to Scala - Blending OO and Functional Paradigms
Miles Sabin
 
PPTX
An introduction to Object Oriented JavaScript
TO THE NEW | Technology
 
PPTX
Scala-Ls1
Aniket Joshi
 
PPT
Scala Talk at FOSDEM 2009
Martin Odersky
 
PDF
Develop realtime web with Scala and Xitrum
Ngoc Dao
 
PDF
Dart workshop
Vishnu Suresh
 
PDF
PL Lecture 01 - preliminaries
Schwannden Kuo
 
PPTX
Unit-1_GHD.pptxguguigihihihihihihoihihhi
40NehaPagariya
 
PDF
Reactive Software Systems
Behrad Zari
 
ODP
Introduction of Object Oriented JavaScript
NexThoughts Technologies
 
Understanding Implicits in Scala
datamantra
 
Functional Programming in Ruby
Alex Teut
 
Functional Programming in JavaScript & ESNext
Unfold UI
 
Python functional programming
Geison Goes
 
Yes scala can!
amirmoulavi
 
Ruby Functional Programming
Geison Goes
 
Introduction to functional programming
Konrad Szydlo
 
Functional Programming.pptx
KarthickT28
 
Java 8
vilniusjug
 
(3) cpp procedural programming
Nico Ludwig
 
An Introduction to Scala - Blending OO and Functional Paradigms
Miles Sabin
 
An introduction to Object Oriented JavaScript
TO THE NEW | Technology
 
Scala-Ls1
Aniket Joshi
 
Scala Talk at FOSDEM 2009
Martin Odersky
 
Develop realtime web with Scala and Xitrum
Ngoc Dao
 
Dart workshop
Vishnu Suresh
 
PL Lecture 01 - preliminaries
Schwannden Kuo
 
Unit-1_GHD.pptxguguigihihihihihihoihihhi
40NehaPagariya
 
Reactive Software Systems
Behrad Zari
 
Introduction of Object Oriented JavaScript
NexThoughts Technologies
 

More from datamantra (19)

PPTX
Multi Source Data Analysis using Spark and Tellius
datamantra
 
PPTX
State management in Structured Streaming
datamantra
 
PDF
Spark on Kubernetes
datamantra
 
PDF
Understanding transactional writes in datasource v2
datamantra
 
PDF
Introduction to Datasource V2 API
datamantra
 
PDF
Exploratory Data Analysis in Spark
datamantra
 
PDF
Core Services behind Spark Job Execution
datamantra
 
PDF
Optimizing S3 Write-heavy Spark workloads
datamantra
 
PDF
Structured Streaming with Kafka
datamantra
 
PDF
Understanding time in structured streaming
datamantra
 
PDF
Spark stack for Model life-cycle management
datamantra
 
PDF
Productionalizing Spark ML
datamantra
 
PDF
Introduction to Structured streaming
datamantra
 
PPTX
Building real time Data Pipeline using Spark Streaming
datamantra
 
PDF
Testing Spark and Scala
datamantra
 
PDF
Migrating to Spark 2.0 - Part 2
datamantra
 
PDF
Migrating to spark 2.0
datamantra
 
PDF
Scalable Spark deployment using Kubernetes
datamantra
 
PDF
Anatomy of Spark SQL Catalyst - Part 2
datamantra
 
Multi Source Data Analysis using Spark and Tellius
datamantra
 
State management in Structured Streaming
datamantra
 
Spark on Kubernetes
datamantra
 
Understanding transactional writes in datasource v2
datamantra
 
Introduction to Datasource V2 API
datamantra
 
Exploratory Data Analysis in Spark
datamantra
 
Core Services behind Spark Job Execution
datamantra
 
Optimizing S3 Write-heavy Spark workloads
datamantra
 
Structured Streaming with Kafka
datamantra
 
Understanding time in structured streaming
datamantra
 
Spark stack for Model life-cycle management
datamantra
 
Productionalizing Spark ML
datamantra
 
Introduction to Structured streaming
datamantra
 
Building real time Data Pipeline using Spark Streaming
datamantra
 
Testing Spark and Scala
datamantra
 
Migrating to Spark 2.0 - Part 2
datamantra
 
Migrating to spark 2.0
datamantra
 
Scalable Spark deployment using Kubernetes
datamantra
 
Anatomy of Spark SQL Catalyst - Part 2
datamantra
 

Recently uploaded (20)

PPTX
Data Security Breach: Immediate Action Plan
varmabhuvan266
 
PPTX
The whitetiger novel review for collegeassignment.pptx
DhruvPatel754154
 
PDF
Chad Readey - An Independent Thinker
Chad Readey
 
PDF
TIC ACTIVIDAD 1geeeeeeeeeeeeeeeeeeeeeeeeeeeeeer3.pdf
Thais Ruiz
 
PPTX
Analysis of Employee_Attrition_Presentation.pptx
AdawuRedeemer
 
PPTX
Azure Data management Engineer project.pptx
sumitmundhe77
 
PDF
Technical Writing Module-I Complete Notes.pdf
VedprakashArya13
 
PPTX
Introduction to Biostatistics Presentation.pptx
AtemJoshua
 
PDF
Company Presentation pada Perusahaan ADB.pdf
didikfahmi
 
PPTX
INFO8116 - Week 10 - Slides.pptx big data architecture
guddipatel10
 
PPTX
Presentation (1) (1).pptx k8hhfftuiiigff
karthikjagath2005
 
PPTX
Introduction to Data Analytics and Data Science
KavithaCIT
 
PDF
CH2-MODEL-SETUP-v2017.1-JC-APR27-2017.pdf
jcc00023con
 
PDF
The_Future_of_Data_Analytics_by_CA_Suvidha_Chaplot_UPDATED.pdf
CA Suvidha Chaplot
 
PDF
Company Profile 2023 PT. ZEKON INDONESIA.pdf
hendranofriadi26
 
PPTX
artificial intelligence deeplearning-200712115616.pptx
revathi148366
 
PDF
Blue Futuristic Cyber Security Presentation.pdf
tanvikhunt1003
 
PDF
345_IT infrastructure for business management.pdf
LEANHTRAN4
 
PPTX
Extract Transformation Load (3) (1).pptx
revathi148366
 
PPTX
Web dev -ppt that helps us understand web technology
shubhragoyal12
 
Data Security Breach: Immediate Action Plan
varmabhuvan266
 
The whitetiger novel review for collegeassignment.pptx
DhruvPatel754154
 
Chad Readey - An Independent Thinker
Chad Readey
 
TIC ACTIVIDAD 1geeeeeeeeeeeeeeeeeeeeeeeeeeeeeer3.pdf
Thais Ruiz
 
Analysis of Employee_Attrition_Presentation.pptx
AdawuRedeemer
 
Azure Data management Engineer project.pptx
sumitmundhe77
 
Technical Writing Module-I Complete Notes.pdf
VedprakashArya13
 
Introduction to Biostatistics Presentation.pptx
AtemJoshua
 
Company Presentation pada Perusahaan ADB.pdf
didikfahmi
 
INFO8116 - Week 10 - Slides.pptx big data architecture
guddipatel10
 
Presentation (1) (1).pptx k8hhfftuiiigff
karthikjagath2005
 
Introduction to Data Analytics and Data Science
KavithaCIT
 
CH2-MODEL-SETUP-v2017.1-JC-APR27-2017.pdf
jcc00023con
 
The_Future_of_Data_Analytics_by_CA_Suvidha_Chaplot_UPDATED.pdf
CA Suvidha Chaplot
 
Company Profile 2023 PT. ZEKON INDONESIA.pdf
hendranofriadi26
 
artificial intelligence deeplearning-200712115616.pptx
revathi148366
 
Blue Futuristic Cyber Security Presentation.pdf
tanvikhunt1003
 
345_IT infrastructure for business management.pdf
LEANHTRAN4
 
Extract Transformation Load (3) (1).pptx
revathi148366
 
Web dev -ppt that helps us understand web technology
shubhragoyal12
 

Functional programming in Scala

  • 2. ● Ganesha Yadiyala ● Big data consultant at datamantra.io ● Consult in spark and scala ● [email protected]
  • 3. Agenda ● Programming paradigms ● Functional Programming ● Advantages of FP ● History of Scala ● Basics of scala ● Functional Aspect of Scala
  • 5. Programming Paradigms ● Programming Paradigm is a approach to programming ● It will be based on set of principles or theory ● Different ways of thinking. ● Different types ○ Imperative ○ Functional
  • 6. Imperative Programming Imperative programming is a programming paradigm that uses statements that change a program's state. Example : ● C# ● C++ ● Java
  • 7. Functional Programming A programming style that models computation as the evaluation of expression. Example: ● Haskell ● Erlang ● Lisp ● Clojure
  • 8. Expression vs Statement Expression : evaluated to produce a value without changing state. Statement : executed to update state. Example: Expression -> val isEven = if(x%2 == 0) true else false
  • 9. Example : Statement -> boolean isEven = true if(x%2 == 0) isEven = true else isEven = false
  • 11. History of Functional Programming ● Mathematical abstraction Lambda Calculus was the foundation for functional Programming ● Lambda calculus was developed in 1930s to be used for functional definition, functional application and recursion. ● It states that any computation can be achieved by sending the input to some black box, which produces its result. ● This black box is lambda functions, and in FP it’s functions. ● LISP was the first functional programming language. It was defined by McCarthy in 1958
  • 12. Imperative vs Functional Programming Characteristics Imperative Functional State changes Important Non-existent Order of execution Important Low importance Primary flow control Loops, conditions and method (function) calls Function calls Primary manipulation unit Instances of structures or classes Functions
  • 13. Characteristics of FP ● Immutable data ● Lazy evaluation ● No side effects ● Referential transparency ● Functions are first class citizens
  • 14. Immutable data Mutable Immutable var collection = [1,2,3,4] for ( i = 0; i<collection.length; i++) { collection[i]+=1; } Uses loop for updating collection is updated in place val collection = [1,2,3,4] val newCollection = collection.map(value => value +1) Uses transformation for change Creates a new copy of collection. Leaves collection intact
  • 15. Advantages of FP ● Better modularity ● Shorter code ● Increased developer productivity ● Less number of bugs ● Perfect for distributed computing because of immutability ● Easier debugging
  • 16. Limitations of FP ● Real world programs have to do side effects ● Difficult to understand for the beginner ● Very difficult to debug the nature of lazy evaluation ● Memory intensive
  • 18. Scala History ● Martin Odersky is the creator ● Curious about compilers from beginning ● Created first compiler in 1995 - Pizza ○ Generics,Function pointers, Case class and pattern matching ● Led to javac compiler and generics eventually ○ Java is a strict language and hard to implement these new ideas
  • 19. Scala History cont.. ● 1999 - Started working on a language ○ Combines Object orientation with functional programming ○ Created Funnel language ○ It was not a user friendly language ○ New languages with less libraries are hard to adopt ● In 2001, design for Scala started, released first in 2003 ● Scala is not an extension of Java ● Scala translates into JAVA byte code ● One implementation of .Net compatible version, now out dated
  • 20. Scala Philosophy ● Growable language ○ Embed new DSL/add new types ● Scalable language ○ Same concepts in small and large applications ● Deep rather than broad ○ Focus on abstraction and composition
  • 21. Why scala ● Hybrid programming language ● Statically typed ● Runs on the jvm ● Can execute java code
  • 23. Everything is an Object ● Supports object oriented programming ● Including primitive types, everything in scala is an object Example: ● val x = 10 ● x.toString()
  • 24. Statically Typed Language ● var message = “hello” ● message = “bye” ● message = 100 //compilation error ● def abs(x:Int) : Int = { ??? } ● abs(“100”) //compilation error
  • 25. Type Inference ● val employeeName : String = “Joy” ● val department = “HR” //Type inferred as String ● val age = 35 //Type inferred as Int
  • 26. Collections ● List,Set,Map etc.. ● Mutable ● Immutable ● Functional API Example: val integerList = List(1,2,3)
  • 28. Operators are also a Function For example ● val sum = 2 + 3 Is same as, ● val sum = 2.+(3) //because ‘+’ operator here is a function
  • 29. Functions in Scala ● Higher order function ● Anonymous function ● Currying ● Tail recursion
  • 30. Defining a Function in Scala ● Defining a function In Scala - def sum(x:Int,y:Int) : Int = x+y In Java - public int sum(int x,int y){ return x+y; }
  • 31. Assigning function to variable Example : def add = (x:Int,y:Int) => x+y add(2,3) //should return 5
  • 32. Higher Order Functions Function that takes functions as a parameters or return function as a result is called higher order functions Example : com.ganesh.functions.HigherOrderFunctions.scala
  • 33. Anonymous Function Scala provides a relatively lightweight syntax for defining anonymous functions. Example: (x: Int) => x + 1 Shorthand for above function is, new Function1[Int, Int] { def apply(x: Int): Int = x + 1 }
  • 34. Currying Currying allows to turn a function that expects two arguments into a function that expects only one, and that function returns a function that expects the second argument. Creating basically a chain of functions. Example : com.ganesh.functions.Currying.scala
  • 35. Implicit Parameters The final parameter list on a method can be marked implicit, which means the values will be taken from the context in which they are called. ● It means that if no value is supplied when called, the compiler will look for an implicit value and pass it in for you. ● Implicits are useful in defining default implementations available. When you need a custom implementation, you can pass one in explicitly. Example : com.ganesh.implicits.Implicits.scala
  • 36. Tail Recursion ● Tail recursion is a special kind of recursion where the recursive call is the very last thing in the function. ● tail-recursive function will only use a single stack frame as opposed to hundreds or even thousands in case of normal recursive function. ● Tail recursion is much faster because it executes using single stack frame Example : com.ganesh.functions.TailRecursion.scala
  • 37. Transformation on Collections We can perform different transformations on collection using collection API. Example: com.ganesh.transformations.SimpleTransformations.scala com.ganesh.transformations.AdvancedTransformations.scala
  • 38. Error Handling Scala does not have checked exceptions like Java, so you can't do something like this to force a programmer to deal with an exception. Example : com.ganesh.exceptionhandling.ExceptionThrowing.scala com.ganesh.exceptionhandling.UsingOptions.scala
  • 39. References ● https://www.coursera.org/learn/progfun1/ - Scala course by Martin Odersky ● http://www.dipmat.unict.it/~barba/PROG-LANG/PROGRAMMI- TESTI/READING-MATERIAL/ShortIntroFPprog-lang.htm - Functional programming and lambda calculus ● Functional Programming in Scala