SlideShare a Scribd company logo
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

More Related Content

What's hot (20)

PPTX
Templates
Farwa Ansari
 
PDF
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
PPTX
Introduction to java 8 stream api
Vladislav sidlyarevich
 
PDF
Learn basics of Clojure/script and Reagent
Maty Fedak
 
PDF
What You Need to Know about Lambdas
Ryan Knight
 
PDF
The... Wonderful? World of Lambdas
Esther Lozano
 
PDF
Functional Principles for OO Developers
jessitron
 
PPTX
Templates presentation
malaybpramanik
 
PDF
RESTful API using scalaz (3)
Yeshwanth Kumar
 
PPTX
New features in jdk8 iti
Ahmed mar3y
 
PDF
Lecture 5: Functional Programming
Eelco Visser
 
PDF
Metaprogramming in Scala 2.10, Eugene Burmako,
Vasil Remeniuk
 
PPT
TechTalk - Dotnet
heinrich.wendel
 
PDF
GUL UC3M - Introduction to functional programming
David Muñoz Díaz
 
PDF
Charles Sharp: Java 8 Streams
jessitron
 
PDF
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
PDF
T3chFest 2016 - The polyglot programmer
David Muñoz Díaz
 
PPTX
Type Driven Development with TypeScript
Garth Gilmour
 
PPT
Java 8 Streams
Manvendra Singh
 
PDF
Demystifying functional programming with Scala
Denis
 
Templates
Farwa Ansari
 
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
Introduction to java 8 stream api
Vladislav sidlyarevich
 
Learn basics of Clojure/script and Reagent
Maty Fedak
 
What You Need to Know about Lambdas
Ryan Knight
 
The... Wonderful? World of Lambdas
Esther Lozano
 
Functional Principles for OO Developers
jessitron
 
Templates presentation
malaybpramanik
 
RESTful API using scalaz (3)
Yeshwanth Kumar
 
New features in jdk8 iti
Ahmed mar3y
 
Lecture 5: Functional Programming
Eelco Visser
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Vasil Remeniuk
 
TechTalk - Dotnet
heinrich.wendel
 
GUL UC3M - Introduction to functional programming
David Muñoz Díaz
 
Charles Sharp: Java 8 Streams
jessitron
 
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
T3chFest 2016 - The polyglot programmer
David Muñoz Díaz
 
Type Driven Development with TypeScript
Garth Gilmour
 
Java 8 Streams
Manvendra Singh
 
Demystifying functional programming with Scala
Denis
 

Similar to Java patterns in Scala (20)

PDF
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
STX Next
 
PDF
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
PDF
Workshop Scala
Bert Van Vreckem
 
PDF
A Sceptical Guide to Functional Programming
Garth Gilmour
 
PPTX
Qcon2011 functions rockpresentation_scala
Michael Stal
 
PPT
Scala uma poderosa linguagem para a jvm
Isaias Barroso
 
ODP
Introduction to Scala
Lorenzo Dematté
 
PPTX
Oop2010 Scala Presentation Stal
Michael Stal
 
ODP
Scala ntnu
Alf Kristian Støyle
 
PPT
Rewriting Java In Scala
Skills Matter
 
PPT
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
PDF
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
PDF
Scala - core features
Łukasz Wójcik
 
PDF
TypeScript Introduction
Dmitry Sheiko
 
ODP
1.2 scala basics
wpgreenway
 
PPTX
Scala
suraj_atreya
 
ODP
Ast transformations
HamletDRC
 
PPTX
A (too) Short Introduction to Scala
Riccardo Cardin
 
PDF
Real world scala
lunfu zhong
 
ODP
1.2 scala basics
futurespective
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
STX Next
 
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
Workshop Scala
Bert Van Vreckem
 
A Sceptical Guide to Functional Programming
Garth Gilmour
 
Qcon2011 functions rockpresentation_scala
Michael Stal
 
Scala uma poderosa linguagem para a jvm
Isaias Barroso
 
Introduction to Scala
Lorenzo Dematté
 
Oop2010 Scala Presentation Stal
Michael Stal
 
Rewriting Java In Scala
Skills Matter
 
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
Scala - core features
Łukasz Wójcik
 
TypeScript Introduction
Dmitry Sheiko
 
1.2 scala basics
wpgreenway
 
Ast transformations
HamletDRC
 
A (too) Short Introduction to Scala
Riccardo Cardin
 
Real world scala
lunfu zhong
 
1.2 scala basics
futurespective
 
Ad

Recently uploaded (20)

PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PPTX
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
Ad

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