SlideShare a Scribd company logo
1 of 48
Download to read offline
Scala
Functioneel programmeren
in een object geörienteerde wereld
Werner Hofstra
Over mij
• Werner Hofstra
• Software dev @ Enshore
• Java, Scala, Clojure, …
Wie is bekend met
• Java
• Object georiënteerd programmeren
• Functioneel programmeren
• Scala
Functioneel programmeren
• Focus op (pure) functies
• Vermijden van side effects
• Immutability
• Vermijden van (re)assignment
Scala
• Static typing
• Object georiënteerd
• Functioneel
• Compileert naar Java bytecode
• Pattern matching
Beloftes
• Elegant
• Expressief
• Concurrency
• Samensmelten OO en FP
Wie gebruikt Scala?
Syntax
object Sounds extends App {
Animal dog = new Dog("Beike")
println(s"Dog: ${dog.name}")
println(dog.makeSound)
}
trait Animal {
def makeSound: String
}
class Dog(val name: String) extends Animal {
override def makeSound: String =
s"$name says WOOF!"
}
public class Sounds {
public static void main(String[] args) {
Animal dog = new Dog("Beike");
System.out.println("Dog: " + dog.getName());
System.out.println(dog.makeSound());
}
}
interface Animal {
String makeSound();
}
class Dog extends Animal {
private String name;
public Dog(String name) {
this.name = name;
}
@Override public String makeSound() {
return getName() + " says WOOF!";
}
public String getName() {
return name;
}
}
Basis
• var
• val
• def
• if
• for
• while
val fordTColor = "Black"
var peugeotColor = "Blue"
peugeotColor = "Gray"
val ferrariColor =
if (ferrari.isRed) "Red"
else "Yellow"
val colors = Array(
"Blue",
"Black",
"Gray",
"White",
)
def printAllColors: Unit = {
for (color <- colors) {
println(color)
}
}
Waarden en
variabelen
• variable
• value
val one = 1
one = 2 // Compileert niet
val oneToFive = 1 to 5
val twoToSix = oneToFive map { _ + 1 }
var two = 2
two = 1 // Ok, maar raar
Immutability
• 4 + 5 = 9
• 4 += 1
• Math.pi = 0
• werner = peter
• Time.now() += 2 hours
Object
Oriented
Programming
• Alles is een object
1 + 2
1.+(2)
"hello".endsWith("lo")
"hello" endsWith "lo"
Object Oriented
Programming
• Alles is een object
• Classes
class Person(val name: String, val age: Int)
Object Oriented
Programming
• Alles is een object
• Classes
• Traits
class Person(val name: String, val age: Int)
trait InsaneSkills {
def listSkills: List(String)
}
Object Oriented Programming
• Alles is een object
• Classes
• Traits
• Inheritance
class Person(val name: String, val age: Int)
trait InsaneSkills {
def listSkills: List(String)
}
class Programmer(
override val name: String,
override val age: Int,
language: String)
extends Person(name, age)
with InsaneSkills {
def listSkills = List(
s"Programming ${language}",
"Giving talks")
}
Traits
• Interfaces
• Implementaties
• Mixins
trait Logger {
def log(msg: String): Unit = {}
}
trait PrintLogger extends Logger {
override def log(msg: String): Unit =
println(msg)
}
class CoffeeMaker extends Logger {
def brew(kind: String): Unit =
log(s"Brewing coffee: $kind")
}
val silently = new CoffeeMaker
silently brew "espresso"
// (geen output)
val loudly = new CoffeeMaker with PrintLogger
loudly brew "espresso"
// Brewing coffee: espresso
Singletons
• Slechts 1 instantie
• Voor static methoden
• Geen constructor args
object MyRandom {
import scala.util.Random
def nextIntBetween(from: Int, to: Int): Int =
Random.nextInt(to - from) + from
}
Types
• Type inference
• Static types
// hello :: String
val hello = "Hello"
// world :: String
val world: String = "World"
// strings :: List[String]
val strings = List(hello, world)
// werner :: Programmer
val werner = new Programmer(
"werner",
28,
"Scala")
Tuples
// tuple :: (Int, String)
val tupleOne = (1, "one")
// tupleTwo :: (Programmer, (Int, String))
val tupleTwo = (werner, tupleOne)
Functies
• ‘First class citizens’
• Hebben ook types
// addOne :: Int => Int
def addOne(x: Int) = x + 2
// addLengths :: (String, String) => Int
def addLengths(s1: String, s2: String) =
s1.length + s2.length
// addLengths2 :: String => (String => Int)
def addLengths2(s1: String)(s2: String) =
s1.length + s2.length
Anonieme
functies
• Functies zonder naam
• Handig voor HOF
val add =
(x: Int, y: Int) => x + y
add(1, 2)
// 3
Hogere orde
functies
• Functies in argumenten
• Functies uit functies
Hogere orde functies
• Functies uit functies
// makeAdder :: Int => (Int => Int)
val makeAdder = {
x: Int => {
y: Int => x + y
}
}
// add5 :: Int => Int
val add5 = makeAdder(5)
// eleven :: Int
val eleven = add5(6)
// 11
Hogere orde functies
• Functies uit functies
• Functies in argumenten
def foreach(fn: Int => Unit, xs: List[Int]) =
for (x <- xs) fn(x)
foreach(println, List(1, 2, 3))
Hogere orde functies
val strings = List("one", "two", "three")
strings map { str => str.toUpperCase }
// List("ONE", "TWO", "THREE")
strings filter { _.length == 3 }
// List("one", "two")
strings.foldLeft("zero") { _ + " " + _ }
// "zero one two three"
strings foreach println
// ()
Hogere orde functies
val strings = List("one", "two", "three")
val numbers = List(1, 2, 3)
(numbers zip strings).toMap
// Map(1 -> "one", 2 -> "two", 3 -> "three")
strings partition { _.length < 4 }
// (List("one", "two"), List("three"))
strings takeWhile { _.length < 4 }
// List("one", "two")
strings dropWhile { _.length < 4 }
// List("three")
Pattern
matching
• Switch on steroids
1 match {
case 1 => "one"
case 2 => "two"
}
// "one"
(1, "one") match {
case (2, string) => "first"
case (1, string) => "second"
case (_, "one") => "third"
case (1, "one") => "fourth"
case _ => "no match"
}
Pattern matching
sealed trait Job
case object Sales extends Job
case object Boss extends Job
case class Programmer(lang: String) extends Job
case class Employee(name: String, job: Job)
val henry = Employee("Henry", Programmer("Scala"))
val james = Employee("James", Boss)
val peter = Employee("Peter", Sales)
henry.job match {
case Boss => "bossing around"
case Sales => "selling stuff"
case Programmer(lang) => s"programming $lang"
}
null
new Garage().getCar(“Ferrari”)
.navigationSystem()
.routeTo("Berlin")
.plan();
null
RoutePlan plan = null;
Car car = new Garage().getCar("Ferrari");
if (car != null) {
NavSystem nav = ferrari.navSystem();
if (nav != null) {
Route route = nav.routeTo("Berlin");
if (route != null) {
plan = route.plan();
}
}
}
Option
• Geeft aan dat iets optioneel is
• Trait
• Case classes: Some(x: Any), None
null vs Option
val garage = new Garage()
val routePlan = for {
//Car <- Option[Car]
car <- garage.getCar("Ferrari")
//NavSystem <- Option[NavSystem]
nav <- car.navigationSystem
//Route <- Option[Route]
route <- nav.routeTo("Berlin")
//RoutePlan <- Option[RoutePlan]
plan <- route.plan
//RoutePlan -> Option[RoutePlan]
} yield plan
null vs Option
val garage = new Garage()
val routePlan = for {
car <- garage.getCar("Ferrari")
nav <- car.navigationSystem
route <- nav.routeTo("Berlin")
plan <- route.plan
} yield plan
QuickSort
• Sorteeralgoritme
• O(n log n) performance
QuickSort
• Neem een lijst met getallen
• Neem een getal ‘x’ uit deze lijst
• Uit de rest van de lijst:
• Zet de getallen lager dan ‘x’ voor ‘x’ en sorteer
• Zet de getallen hoger dan ‘x’ na ‘x’ en sorteer
QuickSort
• Recursieve functie
• Base case: Lege lijst
• Andere cases: Niet-lege lijst
• Manier om lijst op te delen o.b.v. predikaat
• Hogere orde functies!
QuickSort
• Lijst: [5, 3, 10, 7, 1]
• x: 5, rest: [3, 10, 7, 1]
• sort([3, 1]) 5 sort([10, 7])
QuickSort
• [3, 1]
• x: 3, rest: [1]
• sort([1]) 3 sort([])
QuickSort
• [1]
• x: 1, rest: []
• sort([]) 1 sort([])
• [] 1 []
• [1]
QuickSort
• [3, 1]
• x: 3, rest: [1]
• sort([1]) 3 sort([])
• [1] 3 []
• [1, 3]
QuickSort
• Lijst: [5, 3, 10, 7, 1]
• x: 5, rest: [3, 10, 7, 1]
• sort([3, 1]) 5 sort([10, 7])
• [1, 3] 5 sort([10, 7])
• [1, 3] 5 [7, 10]
• [1, 3, 5, 7, 10]
QuickSort
def qsort(ints: List[Int]): List[Int] =
ints match {
case Nil => Nil
case head :: tail => {
val (lower, higher) = tail partition { _ < head }
qsort(lower) ++ (head :: qsort(higher))
}
}
QuickSort
def qsort(ints: List[Int]): List[Int] =
ints match {
case Nil => Nil
case head :: tail => {
val (lower, higher) = tail partition { _ < head }
qsort(lower) ++ (head :: qsort(higher))
}
}
QuickSort
def qsort(ints: List[Int]): List[Int] =
ints match {
case Nil => Nil
case head :: tail => {
val (lower, higher) = tail partition { _ < head }
qsort(lower) ++ (head :: qsort(higher))
}
}
QuickSort
def qsort(ints: List[Int]): List[Int] =
ints match {
case Nil => Nil
case head :: tail => {
val (lower, higher) = tail partition { _ < head }
qsort(lower) ++ (head :: qsort(higher))
}
}
QuickSort
def qsort(ints: List[Int]): List[Int] =
ints match {
case Nil => Nil
case head :: tail => {
val (lower, higher) = tail partition { _ < head }
qsort(lower) ++ (head :: qsort(higher))
}
}
QuickSort
def qsort(ints: List[Int]): List[Int] =
ints match {
case Nil => Nil
case head :: tail => {
val (lower, higher) = tail partition { _ < head }
qsort(lower) ++ (head :: qsort(higher))
}
}
Vragen?

More Related Content

What's hot

Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With ScalaTomer Gabel
 
ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021Jorge Vásquez
 
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaExploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaJorge Vásquez
 
Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Jorge Vásquez
 
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 WorldBTI360
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalazoxbow_lakes
 
Deriving Scalaz
Deriving ScalazDeriving Scalaz
Deriving Scalaznkpart
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in ScalaShai Yallin
 
Scala-对Java的修正和超越
Scala-对Java的修正和超越Scala-对Java的修正和超越
Scala-对Java的修正和超越Caoyuan Deng
 
Exploring type level programming in Scala
Exploring type level programming in ScalaExploring type level programming in Scala
Exploring type level programming in ScalaJorge Vásquez
 
A Scala Corrections Library
A Scala Corrections LibraryA Scala Corrections Library
A Scala Corrections LibraryPaul Phillips
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Brief tour of psp-std
Brief tour of psp-stdBrief tour of psp-std
Brief tour of psp-stdPaul Phillips
 

What's hot (20)

Scala for Jedi
Scala for JediScala for Jedi
Scala for Jedi
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With Scala
 
Scalaz
ScalazScalaz
Scalaz
 
ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021
 
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaExploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in Scala
 
Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!
 
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
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalaz
 
Deriving Scalaz
Deriving ScalazDeriving Scalaz
Deriving Scalaz
 
Scala in Practice
Scala in PracticeScala in Practice
Scala in Practice
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
 
Scala-对Java的修正和超越
Scala-对Java的修正和超越Scala-对Java的修正和超越
Scala-对Java的修正和超越
 
Scala intro workshop
Scala intro workshopScala intro workshop
Scala intro workshop
 
Exploring type level programming in Scala
Exploring type level programming in ScalaExploring type level programming in Scala
Exploring type level programming in Scala
 
A Scala Corrections Library
A Scala Corrections LibraryA Scala Corrections Library
A Scala Corrections Library
 
Groovy unleashed
Groovy unleashed Groovy unleashed
Groovy unleashed
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Brief tour of psp-std
Brief tour of psp-stdBrief tour of psp-std
Brief tour of psp-std
 

Viewers also liked

Img x04113631-0001
Img x04113631-0001Img x04113631-0001
Img x04113631-0001grade5a
 
Wipro data center video cover slide
Wipro data center video cover slideWipro data center video cover slide
Wipro data center video cover slidethomasdenning
 
Edital de seleção do mestrado em letras cameam- uern 010.2012
Edital de seleção do mestrado em letras   cameam- uern 010.2012Edital de seleção do mestrado em letras   cameam- uern 010.2012
Edital de seleção do mestrado em letras cameam- uern 010.2012Tarso Costa
 
Confit de pato a la naranja con platano
Confit de pato a la naranja con platanoConfit de pato a la naranja con platano
Confit de pato a la naranja con platanoTrades
 
Linkedin profile
Linkedin profileLinkedin profile
Linkedin profilesemzoom
 
Engineers And Technicians For Germany
Engineers And Technicians For GermanyEngineers And Technicians For Germany
Engineers And Technicians For GermanyCande Krause
 
Extra vitamines slikken vaak niet nodig
Extra vitamines slikken vaak niet nodigExtra vitamines slikken vaak niet nodig
Extra vitamines slikken vaak niet nodigresonanttermino77
 
Festival gastronômico e cultural de Salinas de Margarida-BA, 27 a 31.12.13
Festival gastronômico e cultural  de Salinas de Margarida-BA, 27 a 31.12.13Festival gastronômico e cultural  de Salinas de Margarida-BA, 27 a 31.12.13
Festival gastronômico e cultural de Salinas de Margarida-BA, 27 a 31.12.13TvSaj
 

Viewers also liked (20)

Img x04113631-0001
Img x04113631-0001Img x04113631-0001
Img x04113631-0001
 
Unidade i
Unidade iUnidade i
Unidade i
 
Dean Professional Offices
Dean Professional OfficesDean Professional Offices
Dean Professional Offices
 
Prova usos
Prova usosProva usos
Prova usos
 
Wipro data center video cover slide
Wipro data center video cover slideWipro data center video cover slide
Wipro data center video cover slide
 
Edital de seleção do mestrado em letras cameam- uern 010.2012
Edital de seleção do mestrado em letras   cameam- uern 010.2012Edital de seleção do mestrado em letras   cameam- uern 010.2012
Edital de seleção do mestrado em letras cameam- uern 010.2012
 
Confit de pato a la naranja con platano
Confit de pato a la naranja con platanoConfit de pato a la naranja con platano
Confit de pato a la naranja con platano
 
Drawing slight 1
Drawing slight 1Drawing slight 1
Drawing slight 1
 
Cantantes
CantantesCantantes
Cantantes
 
Linkedin profile
Linkedin profileLinkedin profile
Linkedin profile
 
page 30
page 30page 30
page 30
 
Telemili
TelemiliTelemili
Telemili
 
Diseã±o de unidades didã¡cticas con recursos tic
Diseã±o de unidades didã¡cticas con recursos ticDiseã±o de unidades didã¡cticas con recursos tic
Diseã±o de unidades didã¡cticas con recursos tic
 
Ppt gloria
Ppt gloriaPpt gloria
Ppt gloria
 
Minimum wages[1]
Minimum wages[1]Minimum wages[1]
Minimum wages[1]
 
Engineers And Technicians For Germany
Engineers And Technicians For GermanyEngineers And Technicians For Germany
Engineers And Technicians For Germany
 
Extra vitamines slikken vaak niet nodig
Extra vitamines slikken vaak niet nodigExtra vitamines slikken vaak niet nodig
Extra vitamines slikken vaak niet nodig
 
Api
ApiApi
Api
 
Quadern normes-2012
Quadern normes-2012Quadern normes-2012
Quadern normes-2012
 
Festival gastronômico e cultural de Salinas de Margarida-BA, 27 a 31.12.13
Festival gastronômico e cultural  de Salinas de Margarida-BA, 27 a 31.12.13Festival gastronômico e cultural  de Salinas de Margarida-BA, 27 a 31.12.13
Festival gastronômico e cultural de Salinas de Margarida-BA, 27 a 31.12.13
 

Similar to Scala: Functioneel programmeren in een object georiënteerde wereld

(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Jesper Kamstrup Linnet
 
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 perspectivegabalese
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scalaXing
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
ITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingIstanbul Tech Talks
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala Knoldus Inc.
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed worldDebasish Ghosh
 
Scala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitScala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitTomer Gabel
 
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 risksSeniorDevOnly
 

Similar to Scala: Functioneel programmeren in een object georiënteerde wereld (20)

Scala
ScalaScala
Scala
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Meet scala
Meet scalaMeet scala
Meet scala
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
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
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
ITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function Programming
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
 
Scala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitScala Refactoring for Fun and Profit
Scala Refactoring for Fun and Profit
 
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
 

Recently uploaded

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationJuha-Pekka Tolvanen
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 

Recently uploaded (20)

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 

Scala: Functioneel programmeren in een object georiënteerde wereld

  • 1. Scala Functioneel programmeren in een object geörienteerde wereld Werner Hofstra
  • 2. Over mij • Werner Hofstra • Software dev @ Enshore • Java, Scala, Clojure, …
  • 3. Wie is bekend met • Java • Object georiënteerd programmeren • Functioneel programmeren • Scala
  • 4. Functioneel programmeren • Focus op (pure) functies • Vermijden van side effects • Immutability • Vermijden van (re)assignment
  • 5. Scala • Static typing • Object georiënteerd • Functioneel • Compileert naar Java bytecode • Pattern matching
  • 6. Beloftes • Elegant • Expressief • Concurrency • Samensmelten OO en FP
  • 8. Syntax object Sounds extends App { Animal dog = new Dog("Beike") println(s"Dog: ${dog.name}") println(dog.makeSound) } trait Animal { def makeSound: String } class Dog(val name: String) extends Animal { override def makeSound: String = s"$name says WOOF!" } public class Sounds { public static void main(String[] args) { Animal dog = new Dog("Beike"); System.out.println("Dog: " + dog.getName()); System.out.println(dog.makeSound()); } } interface Animal { String makeSound(); } class Dog extends Animal { private String name; public Dog(String name) { this.name = name; } @Override public String makeSound() { return getName() + " says WOOF!"; } public String getName() { return name; } }
  • 9. Basis • var • val • def • if • for • while val fordTColor = "Black" var peugeotColor = "Blue" peugeotColor = "Gray" val ferrariColor = if (ferrari.isRed) "Red" else "Yellow" val colors = Array( "Blue", "Black", "Gray", "White", ) def printAllColors: Unit = { for (color <- colors) { println(color) } }
  • 10. Waarden en variabelen • variable • value val one = 1 one = 2 // Compileert niet val oneToFive = 1 to 5 val twoToSix = oneToFive map { _ + 1 } var two = 2 two = 1 // Ok, maar raar
  • 11. Immutability • 4 + 5 = 9 • 4 += 1 • Math.pi = 0 • werner = peter • Time.now() += 2 hours
  • 12. Object Oriented Programming • Alles is een object 1 + 2 1.+(2) "hello".endsWith("lo") "hello" endsWith "lo"
  • 13. Object Oriented Programming • Alles is een object • Classes class Person(val name: String, val age: Int)
  • 14. Object Oriented Programming • Alles is een object • Classes • Traits class Person(val name: String, val age: Int) trait InsaneSkills { def listSkills: List(String) }
  • 15. Object Oriented Programming • Alles is een object • Classes • Traits • Inheritance class Person(val name: String, val age: Int) trait InsaneSkills { def listSkills: List(String) } class Programmer( override val name: String, override val age: Int, language: String) extends Person(name, age) with InsaneSkills { def listSkills = List( s"Programming ${language}", "Giving talks") }
  • 16. Traits • Interfaces • Implementaties • Mixins trait Logger { def log(msg: String): Unit = {} } trait PrintLogger extends Logger { override def log(msg: String): Unit = println(msg) } class CoffeeMaker extends Logger { def brew(kind: String): Unit = log(s"Brewing coffee: $kind") } val silently = new CoffeeMaker silently brew "espresso" // (geen output) val loudly = new CoffeeMaker with PrintLogger loudly brew "espresso" // Brewing coffee: espresso
  • 17. Singletons • Slechts 1 instantie • Voor static methoden • Geen constructor args object MyRandom { import scala.util.Random def nextIntBetween(from: Int, to: Int): Int = Random.nextInt(to - from) + from }
  • 18. Types • Type inference • Static types // hello :: String val hello = "Hello" // world :: String val world: String = "World" // strings :: List[String] val strings = List(hello, world) // werner :: Programmer val werner = new Programmer( "werner", 28, "Scala")
  • 19. Tuples // tuple :: (Int, String) val tupleOne = (1, "one") // tupleTwo :: (Programmer, (Int, String)) val tupleTwo = (werner, tupleOne)
  • 20. Functies • ‘First class citizens’ • Hebben ook types // addOne :: Int => Int def addOne(x: Int) = x + 2 // addLengths :: (String, String) => Int def addLengths(s1: String, s2: String) = s1.length + s2.length // addLengths2 :: String => (String => Int) def addLengths2(s1: String)(s2: String) = s1.length + s2.length
  • 21. Anonieme functies • Functies zonder naam • Handig voor HOF val add = (x: Int, y: Int) => x + y add(1, 2) // 3
  • 22. Hogere orde functies • Functies in argumenten • Functies uit functies
  • 23. Hogere orde functies • Functies uit functies // makeAdder :: Int => (Int => Int) val makeAdder = { x: Int => { y: Int => x + y } } // add5 :: Int => Int val add5 = makeAdder(5) // eleven :: Int val eleven = add5(6) // 11
  • 24. Hogere orde functies • Functies uit functies • Functies in argumenten def foreach(fn: Int => Unit, xs: List[Int]) = for (x <- xs) fn(x) foreach(println, List(1, 2, 3))
  • 25. Hogere orde functies val strings = List("one", "two", "three") strings map { str => str.toUpperCase } // List("ONE", "TWO", "THREE") strings filter { _.length == 3 } // List("one", "two") strings.foldLeft("zero") { _ + " " + _ } // "zero one two three" strings foreach println // ()
  • 26. Hogere orde functies val strings = List("one", "two", "three") val numbers = List(1, 2, 3) (numbers zip strings).toMap // Map(1 -> "one", 2 -> "two", 3 -> "three") strings partition { _.length < 4 } // (List("one", "two"), List("three")) strings takeWhile { _.length < 4 } // List("one", "two") strings dropWhile { _.length < 4 } // List("three")
  • 27. Pattern matching • Switch on steroids 1 match { case 1 => "one" case 2 => "two" } // "one" (1, "one") match { case (2, string) => "first" case (1, string) => "second" case (_, "one") => "third" case (1, "one") => "fourth" case _ => "no match" }
  • 28. Pattern matching sealed trait Job case object Sales extends Job case object Boss extends Job case class Programmer(lang: String) extends Job case class Employee(name: String, job: Job) val henry = Employee("Henry", Programmer("Scala")) val james = Employee("James", Boss) val peter = Employee("Peter", Sales) henry.job match { case Boss => "bossing around" case Sales => "selling stuff" case Programmer(lang) => s"programming $lang" }
  • 30. null RoutePlan plan = null; Car car = new Garage().getCar("Ferrari"); if (car != null) { NavSystem nav = ferrari.navSystem(); if (nav != null) { Route route = nav.routeTo("Berlin"); if (route != null) { plan = route.plan(); } } }
  • 31. Option • Geeft aan dat iets optioneel is • Trait • Case classes: Some(x: Any), None
  • 32. null vs Option val garage = new Garage() val routePlan = for { //Car <- Option[Car] car <- garage.getCar("Ferrari") //NavSystem <- Option[NavSystem] nav <- car.navigationSystem //Route <- Option[Route] route <- nav.routeTo("Berlin") //RoutePlan <- Option[RoutePlan] plan <- route.plan //RoutePlan -> Option[RoutePlan] } yield plan
  • 33. null vs Option val garage = new Garage() val routePlan = for { car <- garage.getCar("Ferrari") nav <- car.navigationSystem route <- nav.routeTo("Berlin") plan <- route.plan } yield plan
  • 35. QuickSort • Neem een lijst met getallen • Neem een getal ‘x’ uit deze lijst • Uit de rest van de lijst: • Zet de getallen lager dan ‘x’ voor ‘x’ en sorteer • Zet de getallen hoger dan ‘x’ na ‘x’ en sorteer
  • 36. QuickSort • Recursieve functie • Base case: Lege lijst • Andere cases: Niet-lege lijst • Manier om lijst op te delen o.b.v. predikaat • Hogere orde functies!
  • 37. QuickSort • Lijst: [5, 3, 10, 7, 1] • x: 5, rest: [3, 10, 7, 1] • sort([3, 1]) 5 sort([10, 7])
  • 38. QuickSort • [3, 1] • x: 3, rest: [1] • sort([1]) 3 sort([])
  • 39. QuickSort • [1] • x: 1, rest: [] • sort([]) 1 sort([]) • [] 1 [] • [1]
  • 40. QuickSort • [3, 1] • x: 3, rest: [1] • sort([1]) 3 sort([]) • [1] 3 [] • [1, 3]
  • 41. QuickSort • Lijst: [5, 3, 10, 7, 1] • x: 5, rest: [3, 10, 7, 1] • sort([3, 1]) 5 sort([10, 7]) • [1, 3] 5 sort([10, 7]) • [1, 3] 5 [7, 10] • [1, 3, 5, 7, 10]
  • 42. QuickSort def qsort(ints: List[Int]): List[Int] = ints match { case Nil => Nil case head :: tail => { val (lower, higher) = tail partition { _ < head } qsort(lower) ++ (head :: qsort(higher)) } }
  • 43. QuickSort def qsort(ints: List[Int]): List[Int] = ints match { case Nil => Nil case head :: tail => { val (lower, higher) = tail partition { _ < head } qsort(lower) ++ (head :: qsort(higher)) } }
  • 44. QuickSort def qsort(ints: List[Int]): List[Int] = ints match { case Nil => Nil case head :: tail => { val (lower, higher) = tail partition { _ < head } qsort(lower) ++ (head :: qsort(higher)) } }
  • 45. QuickSort def qsort(ints: List[Int]): List[Int] = ints match { case Nil => Nil case head :: tail => { val (lower, higher) = tail partition { _ < head } qsort(lower) ++ (head :: qsort(higher)) } }
  • 46. QuickSort def qsort(ints: List[Int]): List[Int] = ints match { case Nil => Nil case head :: tail => { val (lower, higher) = tail partition { _ < head } qsort(lower) ++ (head :: qsort(higher)) } }
  • 47. QuickSort def qsort(ints: List[Int]): List[Int] = ints match { case Nil => Nil case head :: tail => { val (lower, higher) = tail partition { _ < head } qsort(lower) ++ (head :: qsort(higher)) } }