SlideShare ist ein Scribd-Unternehmen logo
1 von 40
Downloaden Sie, um offline zu lesen
Java design patterns in
Scala
Radim Pavlicek
About me
● Java/Scala developer
● bogey golfer
● piano player
Agenda
Part I - OO Patterns
Functional Interface
Command
Builder
Iterator
Template method
Strategy
Null Object
Functional Interface
encapsulate a bit of program logic and treated
like any other first-class construct
Java
Collections.sort(people,
new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return p1.getFirstName().compareTo(
ps.getFirstName())
}
})
Java
other use-cases
● runnable
● callable
Java 8 has solved
Scala
people.sortWith(
(p1, p2) => p1.firstName < p2.firstName
)
Command
Turn a method invocation into an object
and execute it in a central location
Java
public class PrintCommand implements Runnable {
private final String s;
PrintCommand(String s) { this.s = s; }
public void run() { System.out.println(s); }
}
public class Invoker {
private final List<Runnable> history = new ArrayList<>();
void invoke(Runnable command) {
command.run();
history.add(command);
}
}
Invoker invoker = new Invoker();
invoker.invoke( new PrintCommand( "Scala"));
invoker.invoke( new PrintCommand( "Vienna"));
Scala
object Invoker {
private var history: Seq[() => Unit] = Seq.empty
def invoke(command: => Unit) { // by-name parameter
command
history :+= command _
}
}
Invoker.invoke(println( "foo"))
Scala advanced
def makePurchase(register: CaschRegister, amount: Int) =
{
() = {
println("Purchase in amount: " + amount)
register.addCash(amount)
}
}
// how to create purchase functions using closure
Builder
to create an immutable object using a friendly
syntax
Java
Issues
● constructor arguments
Person(String n,String n2,String nick
● Defaults (telescoping constructor problem)
Person()
Person(String name)
Person(String name, String name2)...
Java code
public class ImmutablePerson {
private final String firstName;
public String getFirstName() {
return firstName;}
private ImmetablePerson(Builder builder) {
firstName = builder.firstName;
}
public static Builder newBuilder() {
return new Builder();
}
}
public static class Builder {
private String firstName;
public Builder withFirstName(String
firstName) {
this.firstName = firstName;
return this;
}
public ImmutablePerson build () {
return new ImmutablePerson(this);
}
}
Scala - Case Class
case class Person {
firstName: String,
LastName: String,
nick: String = "")
val p = Person(firstName = “Radim”, lastName = “Pavlicek”)
val cloneMe = Person(firstName = “Radim”, lastName = “Pavlicek”)
p.equals(cloneMe) // true
val brother = p.copy(firstName = “Libor”) // Libor Pavlicek
p.toString // Person[firstName=”Radim”, lastName= “Pavlicek”]
Scala - Tuples
● for explorative development
def p = (“Radim”, “Pavlicek”)
p._1 // Radim
p._2 // Pavlicek
Iterator
iterate through the elements of a sequence
without having to index into it
Java
public Set<Char> vowelsCount(String s) {
Set<Char> l = new HashSet<Char>();
for (Char c : s.toLowerCase().toCharArray())
if (isVowel(c))
l.add(c)
}
Scala
● filter
● map
● reduce
Scala filter
filtering certain elements from collection
def vowelsNumber(word : String) =
word.filter(isVowel).toSet
vowelsNumber(“Radim”) // Set(‘a’, ‘i’)
Scala map
function is applied to each element
def prependHello(names : Seq[String]) =
names.map((name) => “Hello, “ + name)
Scala reduce
reduce sequence to a single value
def sum(sq : Seq[Int]) =
if (sq.isEmpty) 0
else
sq.reduce((acc,curr) => acc + curr)
Scala comprehensions
● guard
for (a <- list if isEven(a))
● pattern matching
for (Person(name, address) <- people)
● still no mutable state
Scala for comprehensions
case class Person(name: String, addr: Address)
case class Address(zip: Int)
def greetings(people: Seq[Person]) =
for (Person(name, address) <-
people if isCloseZip(address.zip) )
yield “Hello, %s”.format(name)
Template method
defines the program skeleton of an algorithm in
a method, called template method, which defers
some steps to subclasses
Java
public abstract class Template {
public void doStuff() {
beforeStuff(); afterStuff();
}
protected abstract void beforeStuff();
protected abstract void afterStuff();
}
Scala Function Builder
def doStuff(
beforeStuff: () => Unit,
afterStuff: () => Unit) =
() = {
beforeSuff()
afterStuff()
}
Scala Function Builder
def beforeStuff() = Console.println(“before”)
def afterStuff() = Console.println(“after”)
val test= doStuff(beforeStuff, afterStuff)
scala> test
Strategy
define an algorithm in abstract terms and make
it interchangeable within family
Java
public interface Strategy {
int compute(int a, int b);
}
public class Add implements Strategy {
public int compute(int a, int b) { return a + b; }
}
public class Multiply implements Strategy {
public int compute(int a, int b) { return a * b; }
}
public class Context {
private final Strategy strategy;
public Context(Strategy strategy) { this.strategy = strategy; }
public void use(int a, int b) { strategy.compute(a, b); }
}
new Context(new Multiply()).use(2, 3);
Scala
define type alias and use first-class functions
type Strategy = (Int, Int) => Int
class Context(computer: Strategy) {
def use(a: Int, b: Int) { computer(a, b) }
}
val add: Strategy = _ + _
val multiply: Strategy = _ * _
new Context(multiply).use( 2, 3)
Null Object
avoid null checks in code and
centralize logic that deals with handling the
absence of a value
Java
class NullPerson extends Person {....}
public Person build(String first, String last) {
if (first == null || last == null)
return new NullPerson();
return new Person (first, last);
}
Scala
val nullPerson = Person() // case class
def build(first: Option[String],
last: Option[String]) =
(for (f <- first; l <- last)
yield Person(f, l)
).getOrElse(nullPerson)
Decorator
add behaviour to an existing class
aka “there is a bug in the API class”
Java
public interface OutputStream {
void write(byte b);
void write(byte[] b);
}
public class FileOutputStream implements OutputStream { /* ... */ }
public abstract class OutputStreamDecorator implements OutputStream {
protected final OutputStream delegate;
protected OutputStreamDecorator(OutputStream delegate) {
this.delegate = delegate;
}
public void write(byte b) { delegate.write(b); }
public void write(byte[] b) { delegate.write(b); }
}
Scala
def add(a: Int, b: Int) = a + b
def decorateLogger(calcF: (Int, Int) => Int) =
(a: Int, b: Int) => {
val result = calcF(a, b)
println(“Result is: “ + result) // here it comes
result
}
Scala
val loggingAdd = decorateLogger(add)
scala> loggingAdd(1,4)
Result is 5
Sources
http://pavelfatin.com/design-patterns-in-scala

Weitere ähnliche Inhalte

Was ist angesagt?

TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
Eelco Visser
 

Was ist angesagt? (20)

Templates
TemplatesTemplates
Templates
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
Learn basics of Clojure/script and Reagent
Learn basics of Clojure/script and ReagentLearn basics of Clojure/script and Reagent
Learn basics of Clojure/script and Reagent
 
What You Need to Know about Lambdas
What You Need to Know about LambdasWhat You Need to Know about Lambdas
What You Need to Know about Lambdas
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
 
Functional Principles for OO Developers
Functional Principles for OO DevelopersFunctional Principles for OO Developers
Functional Principles for OO Developers
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
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,
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
GUL UC3M - Introduction to functional programming
GUL UC3M - Introduction to functional programmingGUL UC3M - Introduction to functional programming
GUL UC3M - Introduction to functional programming
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
T3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerT3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmer
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 

Ähnlich wie Java patterns in Scala

A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
Garth Gilmour
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
wpgreenway
 
Real world scala
Real world scalaReal world scala
Real world scala
lunfu zhong
 

Ähnlich wie Java patterns in Scala (20)

Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In Scala
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
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 - core features
Scala - core featuresScala - core features
Scala - core features
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Scala
ScalaScala
Scala
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to Scala
 
Real world scala
Real world scalaReal world scala
Real world scala
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 

Kürzlich hochgeladen

%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
+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 Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+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
 

Kürzlich hochgeladen (20)

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 Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
%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
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
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
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
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
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
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...
 
+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...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%+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...
 

Java patterns in Scala

  • 1. Java design patterns in Scala Radim Pavlicek
  • 2. About me ● Java/Scala developer ● bogey golfer ● piano player
  • 4. Part I - OO Patterns Functional Interface Command Builder Iterator Template method Strategy Null Object
  • 5. Functional Interface encapsulate a bit of program logic and treated like any other first-class construct
  • 6. Java Collections.sort(people, new Comparator<Person>() { public int compare(Person p1, Person p2) { return p1.getFirstName().compareTo( ps.getFirstName()) } })
  • 7. Java other use-cases ● runnable ● callable Java 8 has solved
  • 8. Scala people.sortWith( (p1, p2) => p1.firstName < p2.firstName )
  • 9. Command Turn a method invocation into an object and execute it in a central location
  • 10. Java public class PrintCommand implements Runnable { private final String s; PrintCommand(String s) { this.s = s; } public void run() { System.out.println(s); } } public class Invoker { private final List<Runnable> history = new ArrayList<>(); void invoke(Runnable command) { command.run(); history.add(command); } } Invoker invoker = new Invoker(); invoker.invoke( new PrintCommand( "Scala")); invoker.invoke( new PrintCommand( "Vienna"));
  • 11. Scala object Invoker { private var history: Seq[() => Unit] = Seq.empty def invoke(command: => Unit) { // by-name parameter command history :+= command _ } } Invoker.invoke(println( "foo"))
  • 12. Scala advanced def makePurchase(register: CaschRegister, amount: Int) = { () = { println("Purchase in amount: " + amount) register.addCash(amount) } } // how to create purchase functions using closure
  • 13. Builder to create an immutable object using a friendly syntax
  • 14. Java Issues ● constructor arguments Person(String n,String n2,String nick ● Defaults (telescoping constructor problem) Person() Person(String name) Person(String name, String name2)...
  • 15. Java code public class ImmutablePerson { private final String firstName; public String getFirstName() { return firstName;} private ImmetablePerson(Builder builder) { firstName = builder.firstName; } public static Builder newBuilder() { return new Builder(); } } public static class Builder { private String firstName; public Builder withFirstName(String firstName) { this.firstName = firstName; return this; } public ImmutablePerson build () { return new ImmutablePerson(this); } }
  • 16. Scala - Case Class case class Person { firstName: String, LastName: String, nick: String = "") val p = Person(firstName = “Radim”, lastName = “Pavlicek”) val cloneMe = Person(firstName = “Radim”, lastName = “Pavlicek”) p.equals(cloneMe) // true val brother = p.copy(firstName = “Libor”) // Libor Pavlicek p.toString // Person[firstName=”Radim”, lastName= “Pavlicek”]
  • 17. Scala - Tuples ● for explorative development def p = (“Radim”, “Pavlicek”) p._1 // Radim p._2 // Pavlicek
  • 18. Iterator iterate through the elements of a sequence without having to index into it
  • 19. Java public Set<Char> vowelsCount(String s) { Set<Char> l = new HashSet<Char>(); for (Char c : s.toLowerCase().toCharArray()) if (isVowel(c)) l.add(c) }
  • 21. Scala filter filtering certain elements from collection def vowelsNumber(word : String) = word.filter(isVowel).toSet vowelsNumber(“Radim”) // Set(‘a’, ‘i’)
  • 22. Scala map function is applied to each element def prependHello(names : Seq[String]) = names.map((name) => “Hello, “ + name)
  • 23. Scala reduce reduce sequence to a single value def sum(sq : Seq[Int]) = if (sq.isEmpty) 0 else sq.reduce((acc,curr) => acc + curr)
  • 24. Scala comprehensions ● guard for (a <- list if isEven(a)) ● pattern matching for (Person(name, address) <- people) ● still no mutable state
  • 25. Scala for comprehensions case class Person(name: String, addr: Address) case class Address(zip: Int) def greetings(people: Seq[Person]) = for (Person(name, address) <- people if isCloseZip(address.zip) ) yield “Hello, %s”.format(name)
  • 26. Template method defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses
  • 27. Java public abstract class Template { public void doStuff() { beforeStuff(); afterStuff(); } protected abstract void beforeStuff(); protected abstract void afterStuff(); }
  • 28. Scala Function Builder def doStuff( beforeStuff: () => Unit, afterStuff: () => Unit) = () = { beforeSuff() afterStuff() }
  • 29. Scala Function Builder def beforeStuff() = Console.println(“before”) def afterStuff() = Console.println(“after”) val test= doStuff(beforeStuff, afterStuff) scala> test
  • 30. Strategy define an algorithm in abstract terms and make it interchangeable within family
  • 31. Java public interface Strategy { int compute(int a, int b); } public class Add implements Strategy { public int compute(int a, int b) { return a + b; } } public class Multiply implements Strategy { public int compute(int a, int b) { return a * b; } } public class Context { private final Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public void use(int a, int b) { strategy.compute(a, b); } } new Context(new Multiply()).use(2, 3);
  • 32. Scala define type alias and use first-class functions type Strategy = (Int, Int) => Int class Context(computer: Strategy) { def use(a: Int, b: Int) { computer(a, b) } } val add: Strategy = _ + _ val multiply: Strategy = _ * _ new Context(multiply).use( 2, 3)
  • 33. Null Object avoid null checks in code and centralize logic that deals with handling the absence of a value
  • 34. Java class NullPerson extends Person {....} public Person build(String first, String last) { if (first == null || last == null) return new NullPerson(); return new Person (first, last); }
  • 35. Scala val nullPerson = Person() // case class def build(first: Option[String], last: Option[String]) = (for (f <- first; l <- last) yield Person(f, l) ).getOrElse(nullPerson)
  • 36. Decorator add behaviour to an existing class aka “there is a bug in the API class”
  • 37. Java public interface OutputStream { void write(byte b); void write(byte[] b); } public class FileOutputStream implements OutputStream { /* ... */ } public abstract class OutputStreamDecorator implements OutputStream { protected final OutputStream delegate; protected OutputStreamDecorator(OutputStream delegate) { this.delegate = delegate; } public void write(byte b) { delegate.write(b); } public void write(byte[] b) { delegate.write(b); } }
  • 38. Scala def add(a: Int, b: Int) = a + b def decorateLogger(calcF: (Int, Int) => Int) = (a: Int, b: Int) => { val result = calcF(a, b) println(“Result is: “ + result) // here it comes result }
  • 39. Scala val loggingAdd = decorateLogger(add) scala> loggingAdd(1,4) Result is 5