SlideShare a Scribd company logo
Scala 101
Beyond Java: JVM FP, July 2014
Shai Yallin, Wix.com
audience.filter(_.usesJava).foreach { member =>
sayHi(member)
}
A short overview of Scala’s features
• A functional/OO programming language that runs on the JVM
• Everything is an object – no primitive types
• Functions are first-class members, every function is a value,
including what is usually an operator*
• Scala is statically-typed and supports type inference
* Some of these are synthetic functions
A short overview of Scala’s features
• Lambda expressions, closures and currying naturally
• Pattern matching
• Multiple inheritance through Traits
• Comprehensive collections library
Determinism via Immutability
Scala encourages everything to be immutable by default:
• Variables (vals)
• Collections
• Value objects (using Case Classes)
Better type safety
• Scala is statically and strongly typed; type inference keeps the
code lean and mean
• Stricter generics (in comparison to Java) provide better compile-
time checks
• Advanced features include structural types and type aliases
Case Classes
Good software engineering makes use of value objects. These need to
encapsulate the way they represent their state, to provide information hiding
and to be easy to maintain.
case class Person(
firstName: String,
lastName: String,
age: Int)
val authorOfPascal = Person("Niklaus", "Wirth", 80)
Case classes give us:
Factory methods Person("Niklaus", "Wirth", 80)
Hashcode authorOfPascal.hashCode == 1423465897
Equals authorOfPascal.equals(authorOfModula) == true
Copy val happyBirthday =
authorOfPascal.copy(age = 81)
Pattern matching Wait for it :-)
Collections
Some collection types:
• Seq (abstract ordered sequence)
• List (linked list)
• Set (yeah, it’s a set)
• Map (dictionary/hash)
A collection can be:
• Immutable / Mutable
• Synchronous / Parallel
Collections
With type inference, trivial to instantiate
val numbers = List(1, 2, 3)
val numbers2 = 1 :: 2 :: 3 :: Nil
val firstNames = Set("john", "mary", "muhammad”)
val caloriesPer100gr = Map(
"bacon" -> 541,
"fries" -> 312,
"lettuce" -> 15 )
Collection functions++ ++: +: /: /:
:+ :: ::: : addString
aggregate andThen apply applyOrElse asInstanceOf
canEqual collect collectFirst combinations companion
compose contains containsSlice copyToArray copyToBuffer
corresponds count diff distinct drop
dropRight dropWhile endsWith exists filter
filterNot find flatMap flatten fold
foldLeft foldRight forall foreach genericBuilder
groupBy grouped hasDefiniteSize head headOption
indexOf indexOfSlice indexWhere indices init
inits intersect isDefinedAt isEmpty isInstanceOf
isTraversableAgain iterator last lastIndexOf lastIndexOfSlice
lastIndexWhere lastOption length lengthCompare lift
map mapConserve max maxBy min
minBy mkString nonEmpty orElse padTo
par partition patch permutations prefixLength
product productArity productElement productIterator productPrefix
reduce reduceLeft reduceLeftOption reduceOption reduceRight
reduceRightOption repr reverse reverseIterator reverseMap
reverse_::: runWith sameElements scan scanLeft
scanRight segmentLength seq size slice
sliding sortBy sortWith sorted span
splitAt startsWith stringPrefix sum tail
tails take takeRight takeWhile to
toArray toBuffer toIndexedSeq toIterable toIterator
toList toMap toSeq toSet toStream
toString toTraversable toVector transpose union
unzip unzip3 updated view withFilter
Collection functions++ ++: +: /: /:
:+ :: ::: : addString
aggregate andThen apply applyOrElse asInstanceOf
canEqual collect collectFirst combinations companion
compose contains containsSlice copyToArray copyToBuffer
corresponds count diff distinct drop
dropRight dropWhile endsWith exists filter
filterNot find flatMap flatten fold
foldLeft foldRight forall foreach genericBuilder
groupBy grouped hasDefiniteSize head headOption
indexOf indexOfSlice indexWhere indices init
inits intersect isDefinedAt isEmpty isInstanceOf
isTraversableAgain iterator last lastIndexOf lastIndexOfSlice
lastIndexWhere lastOption length lengthCompare lift
map mapConserve max maxBy min
minBy mkString nonEmpty orElse padTo
par partition patch permutations prefixLength
product productArity productElement productIterator productPrefix
reduce reduceLeft reduceLeftOption reduceOption reduceRight
reduceRightOption repr reverse reverseIterator reverseMap
reverse_::: runWith sameElements scan scanLeft
scanRight segmentLength seq size slice
sliding sortBy sortWith sorted span
splitAt startsWith stringPrefix sum tail
tails take takeRight takeWhile to
toArray toBuffer toIndexedSeq toIterable toIterator
toList toMap toSeq toSet toStream
toString toTraversable toVector transpose union
unzip unzip3 updated view withFilter
Pattern matching
abstract class Gender
case object Male extends Gender
case object Female extends Gender
abstract class MaritalStatus
case object Single extends MaritalStatus
case object Married extends MaritalStatus
case object Divorced extends MaritalStatus
case object Widowed extends MaritalStatus
case class Person(
firstName: String, lastName: String, age: Int,
gender: Option[ Gender ], maritalStatus: Option[ MaritalStatus ])
Pattern matching
def salutation(p: Person) =
(p.gender, p.maritalStatus) match {
case (Some(Male ), _ ) => "Mr."
case (Some(Female), Some(Single) ) => "Miss"
case (Some(Female), None ) => "Ms."
case (Some(Female), _ ) => "Mrs."
case _ => "Unknown"
}
Functions as 1st-class members
val people = Set(
Person("Niklaus", "Wirth", 80),
Person("Anders", "Hejlsberg", 53),
Person("Martin", "Odersky", 55),
Person("Kenneth", "Thompson", 71))
val toddlers = people.filter(person: Person => person.age <= 3)
val minors = people.filter(person => person.age < 18)
val seniorCitizens = people.filter(_.age >= 65)
val isSenior = { person: Person => person.age >= 65}
val alsoSeniorCitizens = people filter isSenior
No nulls
Scala urges us to declare a possible return value using the Option[T] monad; an
option can be either Some(value) or None, and allows us to assume to it can
never be null. We can use collection semantics to consume an Option[T].
case class Person(
firstName: Option[String],
lastName: Option[String],
age: Option[Int])
val completelyUnknown = Person(None, None, None)
val anonymousAdult = Person(None, None, Some(25))
val agelessPerson = Person(Some("John”), Some("Doe"), None)
def ageOf(p: Person): Int = p.age // Won't compile!
def unsafeAgeOf(p: Person): Int = p.age.get // What if age is unknown?
def ageOrZero(p: Person): Int = p.age.getOrElse(0)
Multiple Inheritance with Traits
Similar (but better than) Java 8’s interfaces with default
methods, a Scala class can extend multiple Traits; in case
of collision, the right-most trait wins.
Example: Logging
import org.slf4j._
class ClassWithLogs {
private val log = LoggerFactory.getLogger(this.getClass)
def getNormalizedName(person: Person) = {
log.info("getNormalizedName called")
log.debug("Normalizing " + person)
val normalizedName = person.firstName.toUpperCase.trim
log.debug("Normalized name is: " + normalizedName)
normalizedName
}
}
x1000 classes
Eagerly evaluated
Example: Logging
trait Logging {
private val log = LoggerFactory.getLogger(this.getClass)
protected def logInfo(message: => String) =
if (log.isInfoEnabled) log.info (message)
protected def logDebug(message: => String) =
if (log.isDebugEnabled) log.debug(message)
protected def logWarn(message: => String) =
if (log.isWarnEnabled) log.warn (message)
protected def logError(message: => String) =
if (log.isErrorEnabled) log.error(message)
}
By-name parameters
(lazily evaluated)
Demo Time!
Questions?
shaiy@wix.com
http://www.shaiyallin.com
@shaiyallin

More Related Content

What's hot (20)

Scala introduction
Scala introductionScala introduction
Scala introduction
vito jeng
 
Ankara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with ScalaAnkara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with Scala
Ensar Basri Kahveci
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
Tim Underwood
 
Functional Programming in Scala
Functional Programming in ScalaFunctional Programming in Scala
Functional Programming in Scala
Bassam Abd El Hameed
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
Rémy-Christophe Schermesser
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
BTI360
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
Kelsey Gilmore-Innis
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
Vasil Remeniuk
 
Functional Programming In Practice
Functional Programming In PracticeFunctional Programming In Practice
Functional Programming In Practice
Michiel Borkent
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
Tim (dev-tim) Zadorozhniy
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
John De Goes
 
SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.
Ruslan Shevchenko
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the future
AnsviaLab
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
Eric Pederson
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene Burmako
Vasil Remeniuk
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
vito jeng
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
Łukasz Bałamut
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog
3Pillar Global
 
Scala introduction
Scala introductionScala introduction
Scala introduction
vito jeng
 
Ankara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with ScalaAnkara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with Scala
Ensar Basri Kahveci
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
Tim Underwood
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
BTI360
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
Kelsey Gilmore-Innis
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
Vasil Remeniuk
 
Functional Programming In Practice
Functional Programming In PracticeFunctional Programming In Practice
Functional Programming In Practice
Michiel Borkent
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
John De Goes
 
SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.
Ruslan Shevchenko
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the future
AnsviaLab
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
Eric Pederson
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene Burmako
Vasil Remeniuk
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
vito jeng
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog
3Pillar Global
 

Similar to Intro to Functional Programming in Scala (20)

Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Aleksandar Prokopec
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
Vladimir Parfinenko
 
Scala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectiveScala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspective
gabalese
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
Alf Kristian Støyle
 
Meet scala
Meet scalaMeet scala
Meet scala
Wojciech Pituła
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos
3Pillar Global
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
Neelkanth Sachdeva
 
Scala for Java Developers (Silicon Valley Code Camp 13)
Scala for Java Developers (Silicon Valley Code Camp 13)Scala for Java Developers (Silicon Valley Code Camp 13)
Scala for Java Developers (Silicon Valley Code Camp 13)
Ramnivas Laddad
 
Scala Quick Introduction
Scala Quick IntroductionScala Quick Introduction
Scala Quick Introduction
Damian Jureczko
 
Scala Intro
Scala IntroScala Intro
Scala Intro
Alexey (Mr_Mig) Migutsky
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
Innar Made
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
Łukasz Wójcik
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
SeniorDevOnly
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
Mukesh Kumar
 
Scala Intro
Scala IntroScala Intro
Scala Intro
Paolo Platter
 
Scala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectiveScala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspective
gabalese
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos
3Pillar Global
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
Neelkanth Sachdeva
 
Scala for Java Developers (Silicon Valley Code Camp 13)
Scala for Java Developers (Silicon Valley Code Camp 13)Scala for Java Developers (Silicon Valley Code Camp 13)
Scala for Java Developers (Silicon Valley Code Camp 13)
Ramnivas Laddad
 
Scala Quick Introduction
Scala Quick IntroductionScala Quick Introduction
Scala Quick Introduction
Damian Jureczko
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
Innar Made
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
SeniorDevOnly
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
Mukesh Kumar
 
Ad

Recently uploaded (20)

IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdfHow to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
QuickBooks Training
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptxHow AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
kalichargn70th171
 
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Prachi Desai
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI SearchAgentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Maxim Salnikov
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...
Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...
Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...
Safe Software
 
Online Queue Management System for Public Service Offices [Focused on Municip...
Online Queue Management System for Public Service Offices [Focused on Municip...Online Queue Management System for Public Service Offices [Focused on Municip...
Online Queue Management System for Public Service Offices [Focused on Municip...
Rishab Acharya
 
Simplify Training with an Online Induction Portal for Contractors
Simplify Training with an Online Induction Portal for ContractorsSimplify Training with an Online Induction Portal for Contractors
Simplify Training with an Online Induction Portal for Contractors
SHEQ Network Limited
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Scalefusion Remote Access for Apple Devices
Scalefusion Remote Access for Apple DevicesScalefusion Remote Access for Apple Devices
Scalefusion Remote Access for Apple Devices
Scalefusion
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
Design by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First DevelopmentDesign by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First Development
Par-Tec S.p.A.
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdfHow to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
QuickBooks Training
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptxHow AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
kalichargn70th171
 
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Prachi Desai
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI SearchAgentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Maxim Salnikov
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...
Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...
Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...
Safe Software
 
Online Queue Management System for Public Service Offices [Focused on Municip...
Online Queue Management System for Public Service Offices [Focused on Municip...Online Queue Management System for Public Service Offices [Focused on Municip...
Online Queue Management System for Public Service Offices [Focused on Municip...
Rishab Acharya
 
Simplify Training with an Online Induction Portal for Contractors
Simplify Training with an Online Induction Portal for ContractorsSimplify Training with an Online Induction Portal for Contractors
Simplify Training with an Online Induction Portal for Contractors
SHEQ Network Limited
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Scalefusion Remote Access for Apple Devices
Scalefusion Remote Access for Apple DevicesScalefusion Remote Access for Apple Devices
Scalefusion Remote Access for Apple Devices
Scalefusion
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
Design by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First DevelopmentDesign by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First Development
Par-Tec S.p.A.
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
Ad

Intro to Functional Programming in Scala

  • 1. Scala 101 Beyond Java: JVM FP, July 2014 Shai Yallin, Wix.com audience.filter(_.usesJava).foreach { member => sayHi(member) }
  • 2. A short overview of Scala’s features • A functional/OO programming language that runs on the JVM • Everything is an object – no primitive types • Functions are first-class members, every function is a value, including what is usually an operator* • Scala is statically-typed and supports type inference * Some of these are synthetic functions
  • 3. A short overview of Scala’s features • Lambda expressions, closures and currying naturally • Pattern matching • Multiple inheritance through Traits • Comprehensive collections library
  • 4. Determinism via Immutability Scala encourages everything to be immutable by default: • Variables (vals) • Collections • Value objects (using Case Classes)
  • 5. Better type safety • Scala is statically and strongly typed; type inference keeps the code lean and mean • Stricter generics (in comparison to Java) provide better compile- time checks • Advanced features include structural types and type aliases
  • 6. Case Classes Good software engineering makes use of value objects. These need to encapsulate the way they represent their state, to provide information hiding and to be easy to maintain. case class Person( firstName: String, lastName: String, age: Int) val authorOfPascal = Person("Niklaus", "Wirth", 80)
  • 7. Case classes give us: Factory methods Person("Niklaus", "Wirth", 80) Hashcode authorOfPascal.hashCode == 1423465897 Equals authorOfPascal.equals(authorOfModula) == true Copy val happyBirthday = authorOfPascal.copy(age = 81) Pattern matching Wait for it :-)
  • 8. Collections Some collection types: • Seq (abstract ordered sequence) • List (linked list) • Set (yeah, it’s a set) • Map (dictionary/hash) A collection can be: • Immutable / Mutable • Synchronous / Parallel
  • 9. Collections With type inference, trivial to instantiate val numbers = List(1, 2, 3) val numbers2 = 1 :: 2 :: 3 :: Nil val firstNames = Set("john", "mary", "muhammad”) val caloriesPer100gr = Map( "bacon" -> 541, "fries" -> 312, "lettuce" -> 15 )
  • 10. Collection functions++ ++: +: /: /: :+ :: ::: : addString aggregate andThen apply applyOrElse asInstanceOf canEqual collect collectFirst combinations companion compose contains containsSlice copyToArray copyToBuffer corresponds count diff distinct drop dropRight dropWhile endsWith exists filter filterNot find flatMap flatten fold foldLeft foldRight forall foreach genericBuilder groupBy grouped hasDefiniteSize head headOption indexOf indexOfSlice indexWhere indices init inits intersect isDefinedAt isEmpty isInstanceOf isTraversableAgain iterator last lastIndexOf lastIndexOfSlice lastIndexWhere lastOption length lengthCompare lift map mapConserve max maxBy min minBy mkString nonEmpty orElse padTo par partition patch permutations prefixLength product productArity productElement productIterator productPrefix reduce reduceLeft reduceLeftOption reduceOption reduceRight reduceRightOption repr reverse reverseIterator reverseMap reverse_::: runWith sameElements scan scanLeft scanRight segmentLength seq size slice sliding sortBy sortWith sorted span splitAt startsWith stringPrefix sum tail tails take takeRight takeWhile to toArray toBuffer toIndexedSeq toIterable toIterator toList toMap toSeq toSet toStream toString toTraversable toVector transpose union unzip unzip3 updated view withFilter
  • 11. Collection functions++ ++: +: /: /: :+ :: ::: : addString aggregate andThen apply applyOrElse asInstanceOf canEqual collect collectFirst combinations companion compose contains containsSlice copyToArray copyToBuffer corresponds count diff distinct drop dropRight dropWhile endsWith exists filter filterNot find flatMap flatten fold foldLeft foldRight forall foreach genericBuilder groupBy grouped hasDefiniteSize head headOption indexOf indexOfSlice indexWhere indices init inits intersect isDefinedAt isEmpty isInstanceOf isTraversableAgain iterator last lastIndexOf lastIndexOfSlice lastIndexWhere lastOption length lengthCompare lift map mapConserve max maxBy min minBy mkString nonEmpty orElse padTo par partition patch permutations prefixLength product productArity productElement productIterator productPrefix reduce reduceLeft reduceLeftOption reduceOption reduceRight reduceRightOption repr reverse reverseIterator reverseMap reverse_::: runWith sameElements scan scanLeft scanRight segmentLength seq size slice sliding sortBy sortWith sorted span splitAt startsWith stringPrefix sum tail tails take takeRight takeWhile to toArray toBuffer toIndexedSeq toIterable toIterator toList toMap toSeq toSet toStream toString toTraversable toVector transpose union unzip unzip3 updated view withFilter
  • 12. Pattern matching abstract class Gender case object Male extends Gender case object Female extends Gender abstract class MaritalStatus case object Single extends MaritalStatus case object Married extends MaritalStatus case object Divorced extends MaritalStatus case object Widowed extends MaritalStatus case class Person( firstName: String, lastName: String, age: Int, gender: Option[ Gender ], maritalStatus: Option[ MaritalStatus ])
  • 13. Pattern matching def salutation(p: Person) = (p.gender, p.maritalStatus) match { case (Some(Male ), _ ) => "Mr." case (Some(Female), Some(Single) ) => "Miss" case (Some(Female), None ) => "Ms." case (Some(Female), _ ) => "Mrs." case _ => "Unknown" }
  • 14. Functions as 1st-class members val people = Set( Person("Niklaus", "Wirth", 80), Person("Anders", "Hejlsberg", 53), Person("Martin", "Odersky", 55), Person("Kenneth", "Thompson", 71)) val toddlers = people.filter(person: Person => person.age <= 3) val minors = people.filter(person => person.age < 18) val seniorCitizens = people.filter(_.age >= 65) val isSenior = { person: Person => person.age >= 65} val alsoSeniorCitizens = people filter isSenior
  • 15. No nulls Scala urges us to declare a possible return value using the Option[T] monad; an option can be either Some(value) or None, and allows us to assume to it can never be null. We can use collection semantics to consume an Option[T]. case class Person( firstName: Option[String], lastName: Option[String], age: Option[Int]) val completelyUnknown = Person(None, None, None) val anonymousAdult = Person(None, None, Some(25)) val agelessPerson = Person(Some("John”), Some("Doe"), None) def ageOf(p: Person): Int = p.age // Won't compile! def unsafeAgeOf(p: Person): Int = p.age.get // What if age is unknown? def ageOrZero(p: Person): Int = p.age.getOrElse(0)
  • 16. Multiple Inheritance with Traits Similar (but better than) Java 8’s interfaces with default methods, a Scala class can extend multiple Traits; in case of collision, the right-most trait wins.
  • 17. Example: Logging import org.slf4j._ class ClassWithLogs { private val log = LoggerFactory.getLogger(this.getClass) def getNormalizedName(person: Person) = { log.info("getNormalizedName called") log.debug("Normalizing " + person) val normalizedName = person.firstName.toUpperCase.trim log.debug("Normalized name is: " + normalizedName) normalizedName } } x1000 classes Eagerly evaluated
  • 18. Example: Logging trait Logging { private val log = LoggerFactory.getLogger(this.getClass) protected def logInfo(message: => String) = if (log.isInfoEnabled) log.info (message) protected def logDebug(message: => String) = if (log.isDebugEnabled) log.debug(message) protected def logWarn(message: => String) = if (log.isWarnEnabled) log.warn (message) protected def logError(message: => String) = if (log.isErrorEnabled) log.error(message) } By-name parameters (lazily evaluated)

Editor's Notes

  • #6: Statically typed – types are checked in compile time verses runtime Strongly typed - each variable must have a concrete type You get the best of both worlds – lean code like in dynamic languages and compile-time checking of adherence to structure Type inference can slow down compilation – use with care Structural types – the canonical example is closeable
  • #7: A case class automatically makes its constructor arguments into vals. It also provides automatic equals, hashCode, toString methods and a very useful copy method which makes use of Scala’s named arguments (with defaults) feature. We also see that case classes with proper default argument values are essentially test object builders, which saves us tons of code for test setup