SlideShare a Scribd company logo
Effective Scala
Programming Patterns
The most of the patterns you've got
used to in a traditional OO-languages
(C++, Java, C#) are just language
constructs in a functional languages
The key principle behind the most
of techniques is functional languages is
composition - ability to build assets
that can be reused in different contexts
unknown at the time they created
Pimp My Library
What if you wanted to add new method
for Int?
In Java you would write a wrapper class and use it everywhere
you want your new Int on steroids.

In Scala you would use implicit conversions.

object RichInt {
implicit def intToRichInt(i: Int) = new RichInt(i)
}

class RichInt(private val value: Int) {
def minutes = value + " minutes"
}

// Usage example
import RichInt._
println(10 minutes) //println(intToRichInt(10).minutes)
Pimp My Library

● Simple
● Less boilerplate then ad-hoc conversion
● Can be controlled with scoping
Cell
Guess who's an evil twin
Cell is an object behaving closely like a
normal variable
Implementation details are hidden from end user

Scala has two features in possesion helping us to implement
such a semi-variable:

1. "First class object" functions

 var f: Option[() => Int] = Some(() => 1)

2. Syntactic sugar for update and apply
x() == x.apply()
and
x(<arguments>*) = y == x.update(<arguments>*, y)
Let's design lazy value using Cell pattern
class Lazy[T] { private var v: Option[T] = None private var t: Option[() => T] =
None def update(t: => T) { this.t = Some(t _) v = None } def apply() = { if(v.isEmpty)
v = Some(t.get()) v.get } } val l = new Lazy[Int] l() = { println("Evaluated"); 1} println
("Before evaluated") println(l()) l() = 2 println(l())
Cell actually is

● Simple once again
● Used similar to a variable thanks to syntactic sugar
● Still an object
Type class
Unified factory
import java.util.Date trait Vendor[T] { def vend: T } implicit object
DateVendor extends Vendor[Date] { def vend = new Date } object
Vendor { def vend[T](implicit vendor: Vendor[T]):T = vendor.vend } val
date = Vendor.vend[Date]




This guy is like a one man band.
Tell him a type you wanna play with and he'll hand you off an
instance.
Type class

● Extendable through composition
● Abstracts capabilities from data
● Connects different class hierarchies together
● Controlable with scoping
Duck typing
OMG, we're in J2EE environment
Following dreaded pattern can often be seen in IOC container
environment(well at least when it's a bad one)
class DBDriver class Bean { private var driver: DBDriver = null def getDriver() = driver def setDriver(driver:
DBDriver) { this.driver = driver } } class AnotherBeanFromAnotherParty { private var driver: DBDriver = null
def getDriver() = driver def setDriver(driver:DBDriver) { this.driver = driver } } object Bean extends Bean {
setDriver(new DBDriver) } object AnotherBeanFromAnotherParty extends AnotherBeanFromAnotherParty {
setDriver(new DBDriver) }




Here is how we work this around with structural typing
def extractDriver(bean: { def getDriver(): DBDriver }): DBDriver = bean.getDriver() extractDriver
(Bean) extractDriver(AnotherBeanFromAnotherParty)
Structural typing

 ● Actually a workaround for poorly designed architecture
 ● A typesafe workaround
 ● Follows don't repeat yourself
Cake
Pattern
..."Dependency Injection" is a 25-dollar
term for a 5-cent concept... Dependency
injection means giving an object its instance
variables...
                                James Shore
What do you need dependency injection
for?
 ● reduces coupling between
   components
 ● simplifies configuration of an
   assembly
   ○ useful for unit testing
IoC containers take a simple, elegant, and
useful concept, and make it something you
have to study for two days with a 200-page
manual
                                Joel Spolsky
● in Scala you don't need any DI
  framework - forget Spring and Guice
● you make DI with mixins & self-type
  annotations and no boilerplate
Some code...
http://goo.gl/dWh2i
What's so cool in Cake pattern?

 ● It's not a framework, thus any IDE
   supports it out-of-box
 ● If a dependency is missing, compiler will
   immediately let you know about it
Phantom
 Types
The brain of an average human is used by
only 10% through the lifetime

The type system is used by an
average programmer by only 10% of
its power
Phantom types is a simple yet
powerful way to use the type
system more effectively

2 facts about phantom
types:
● never instantiated
● used only to construct other
  types
Let's say, we need a data type to represent
 the form data extracted from an HTTP
 request:
case class FormData[+T <: Data]
(data: Map[String, String])

trait Data
trait Validated extends Data
trait Unvalidated extends Data


 Validated and Unvalidated are phantom
 types
trait Form {
  val readFormData: HttpServletRequest => FormData
[Unvalidated]

  val validate: FormData[Unvalidated] => FormData
[Validated]

    val printFormData: FormData[Validated] => Any
}


(readFormData andThen validate andThen printFormData)
(request)

(readFormData andThen printFormData)(request) // FAILS!!!
Some code...
http://goo.gl/QAwB3

More Related Content

What's hot (20)

PPTX
Scala - the good, the bad and the very ugly
Bozhidar Bozhanov
 
PDF
Xtext's new Formatter API
meysholdt
 
PPTX
Typescript
Nikhil Thomas
 
PPT
JavaScript: The Language
Engage Software
 
PDF
Compiler2016 by abcdabcd987
乐群 陈
 
PPT
The JavaScript Programming Language
Raghavan Mohan
 
PDF
From DOT to Dotty
Martin Odersky
 
PPTX
2CPP04 - Objects and Classes
Michael Heron
 
PPTX
002. Introducere in type script
Dmitrii Stoian
 
ODP
Getting started with typescript and angular 2
Knoldus Inc.
 
PDF
Working with Cocoa and Objective-C
Kazunobu Tasaka
 
PPTX
“Insulin” for Scala’s Syntactic Diabetes
Tzach Zohar
 
PDF
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
Edureka!
 
KEY
Java Building Blocks
Cate Huston
 
PDF
JavaScript Programming
Sehwan Noh
 
ODP
Scala Reflection & Runtime MetaProgramming
Meir Maor
 
PPTX
All You Need to Know About Type Script
Folio3 Software
 
PPTX
C# 6.0 - DotNetNotts
citizenmatt
 
PPTX
TypeScript
Oswald Campesato
 
PDF
Introduction to Dart
RameshNair6
 
Scala - the good, the bad and the very ugly
Bozhidar Bozhanov
 
Xtext's new Formatter API
meysholdt
 
Typescript
Nikhil Thomas
 
JavaScript: The Language
Engage Software
 
Compiler2016 by abcdabcd987
乐群 陈
 
The JavaScript Programming Language
Raghavan Mohan
 
From DOT to Dotty
Martin Odersky
 
2CPP04 - Objects and Classes
Michael Heron
 
002. Introducere in type script
Dmitrii Stoian
 
Getting started with typescript and angular 2
Knoldus Inc.
 
Working with Cocoa and Objective-C
Kazunobu Tasaka
 
“Insulin” for Scala’s Syntactic Diabetes
Tzach Zohar
 
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
Edureka!
 
Java Building Blocks
Cate Huston
 
JavaScript Programming
Sehwan Noh
 
Scala Reflection & Runtime MetaProgramming
Meir Maor
 
All You Need to Know About Type Script
Folio3 Software
 
C# 6.0 - DotNetNotts
citizenmatt
 
TypeScript
Oswald Campesato
 
Introduction to Dart
RameshNair6
 

Viewers also liked (19)

PPTX
Functional Programming and Concurrency Patterns in Scala
kellogh
 
PPTX
Practical type mining in Scala
Rose Toomey
 
PDF
Testing practicies not only in scala
Paweł Panasewicz
 
PPTX
Joy of scala
Maxim Novak
 
PDF
Scala Types of Types @ Lambda Days
Konrad Malawski
 
PDF
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
PDF
Scala Implicits - Not to be feared
Derek Wyatt
 
PPTX
Akka Fundamentals
Michael Kendra
 
PDF
Introduction to Akka
Johan Andrén
 
ODP
Scal`a`ngular - Scala and Angular
Knoldus Inc.
 
PPTX
Akka Actor presentation
Gene Chang
 
PDF
Akka: Simpler Scalability, Fault-Tolerance, Concurrency & Remoting through Ac...
Jonas Bonér
 
PDF
Akka in 100 slides or less
Derek Wyatt
 
PDF
Introducing Reactive Machine Learning
Jeff Smith
 
PDF
Building Reactive Systems with Akka (in Java 8 or Scala)
Jonas Bonér
 
PDF
Introducing Akka
Jonas Bonér
 
PDF
How to deploy Apache Spark 
to Mesos/DCOS
Legacy Typesafe (now Lightbend)
 
PDF
Akka in Production - ScalaDays 2015
Evan Chan
 
PDF
Spark fulan
TELE-satellite deu
 
Functional Programming and Concurrency Patterns in Scala
kellogh
 
Practical type mining in Scala
Rose Toomey
 
Testing practicies not only in scala
Paweł Panasewicz
 
Joy of scala
Maxim Novak
 
Scala Types of Types @ Lambda Days
Konrad Malawski
 
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
Scala Implicits - Not to be feared
Derek Wyatt
 
Akka Fundamentals
Michael Kendra
 
Introduction to Akka
Johan Andrén
 
Scal`a`ngular - Scala and Angular
Knoldus Inc.
 
Akka Actor presentation
Gene Chang
 
Akka: Simpler Scalability, Fault-Tolerance, Concurrency & Remoting through Ac...
Jonas Bonér
 
Akka in 100 slides or less
Derek Wyatt
 
Introducing Reactive Machine Learning
Jeff Smith
 
Building Reactive Systems with Akka (in Java 8 or Scala)
Jonas Bonér
 
Introducing Akka
Jonas Bonér
 
How to deploy Apache Spark 
to Mesos/DCOS
Legacy Typesafe (now Lightbend)
 
Akka in Production - ScalaDays 2015
Evan Chan
 
Spark fulan
TELE-satellite deu
 
Ad

Similar to Effective Scala: Programming Patterns (20)

PDF
Dsug 05 02-15 - ScalDI - lightweight DI in Scala
Ugo Matrangolo
 
PDF
Design Patterns
adil raja
 
PDF
Scala Self Types by Gregor Heine, Principal Software Engineer at Gilt
Gilt Tech Talks
 
PPT
scala.ppt
Harissh16
 
PDF
Scala Days Highlights | BoldRadius
BoldRadius Solutions
 
PDF
Design Patterns - GOF
Fanus van Straten
 
PDF
The Basic Concept Of IOC
Carl Lu
 
PPTX
L09 Frameworks
Ólafur Andri Ragnarsson
 
PDF
Twins: Object Oriented Programming and Functional Programming
RichardWarburton
 
PDF
TWINS: OOP and FP - Warburton
Codemotion
 
PDF
Reviewing OOP Design patterns
Olivier Bacs
 
PDF
[meetup] Mastering Java enhancements like a Pro: practical design patterns an...
Miro Wengner
 
PDF
So various polymorphism in Scala
b0ris_1
 
PPTX
L05 Frameworks
Ólafur Andri Ragnarsson
 
PDF
Scala - core features
Łukasz Wójcik
 
PPTX
Object Oriented Programming
Manish Pandit
 
PDF
Ankara Jug - Practical Functional Programming with Scala
Ensar Basri Kahveci
 
PPTX
L04 base patterns
Ólafur Andri Ragnarsson
 
PDF
Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...
Isuru Perera
 
PDF
Twins: OOP and FP
RichardWarburton
 
Dsug 05 02-15 - ScalDI - lightweight DI in Scala
Ugo Matrangolo
 
Design Patterns
adil raja
 
Scala Self Types by Gregor Heine, Principal Software Engineer at Gilt
Gilt Tech Talks
 
scala.ppt
Harissh16
 
Scala Days Highlights | BoldRadius
BoldRadius Solutions
 
Design Patterns - GOF
Fanus van Straten
 
The Basic Concept Of IOC
Carl Lu
 
L09 Frameworks
Ólafur Andri Ragnarsson
 
Twins: Object Oriented Programming and Functional Programming
RichardWarburton
 
TWINS: OOP and FP - Warburton
Codemotion
 
Reviewing OOP Design patterns
Olivier Bacs
 
[meetup] Mastering Java enhancements like a Pro: practical design patterns an...
Miro Wengner
 
So various polymorphism in Scala
b0ris_1
 
L05 Frameworks
Ólafur Andri Ragnarsson
 
Scala - core features
Łukasz Wójcik
 
Object Oriented Programming
Manish Pandit
 
Ankara Jug - Practical Functional Programming with Scala
Ensar Basri Kahveci
 
L04 base patterns
Ólafur Andri Ragnarsson
 
Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...
Isuru Perera
 
Twins: OOP and FP
RichardWarburton
 
Ad

More from Vasil Remeniuk (20)

PPTX
Product Minsk - РТБ и Программатик
Vasil Remeniuk
 
PDF
Работа с Akka Сluster, @afiskon, scalaby#14
Vasil Remeniuk
 
PDF
Cake pattern. Presentation by Alex Famin at scalaby#14
Vasil Remeniuk
 
PDF
Scala laboratory: Globus. iteration #3
Vasil Remeniuk
 
PPTX
Testing in Scala by Adform research
Vasil Remeniuk
 
PPTX
Spark Intro by Adform Research
Vasil Remeniuk
 
PPTX
Types by Adform Research, Saulius Valatka
Vasil Remeniuk
 
PPTX
Types by Adform Research
Vasil Remeniuk
 
PPTX
Scalding by Adform Research, Alex Gryzlov
Vasil Remeniuk
 
PPTX
Scalding by Adform Research, Alex Gryzlov
Vasil Remeniuk
 
PPTX
Spark by Adform Research, Paulius
Vasil Remeniuk
 
PPTX
Scala Style by Adform Research (Saulius Valatka)
Vasil Remeniuk
 
PPTX
Spark intro by Adform Research
Vasil Remeniuk
 
PPTX
SBT by Aform Research, Saulius Valatka
Vasil Remeniuk
 
PDF
Scala laboratory: Globus. iteration #2
Vasil Remeniuk
 
PPTX
Testing in Scala. Adform Research
Vasil Remeniuk
 
PDF
Scala laboratory. Globus. iteration #1
Vasil Remeniuk
 
PDF
Cassandra + Spark + Elk
Vasil Remeniuk
 
PDF
Опыт использования Spark, Основано на реальных событиях
Vasil Remeniuk
 
PDF
ETL со Spark
Vasil Remeniuk
 
Product Minsk - РТБ и Программатик
Vasil Remeniuk
 
Работа с Akka Сluster, @afiskon, scalaby#14
Vasil Remeniuk
 
Cake pattern. Presentation by Alex Famin at scalaby#14
Vasil Remeniuk
 
Scala laboratory: Globus. iteration #3
Vasil Remeniuk
 
Testing in Scala by Adform research
Vasil Remeniuk
 
Spark Intro by Adform Research
Vasil Remeniuk
 
Types by Adform Research, Saulius Valatka
Vasil Remeniuk
 
Types by Adform Research
Vasil Remeniuk
 
Scalding by Adform Research, Alex Gryzlov
Vasil Remeniuk
 
Scalding by Adform Research, Alex Gryzlov
Vasil Remeniuk
 
Spark by Adform Research, Paulius
Vasil Remeniuk
 
Scala Style by Adform Research (Saulius Valatka)
Vasil Remeniuk
 
Spark intro by Adform Research
Vasil Remeniuk
 
SBT by Aform Research, Saulius Valatka
Vasil Remeniuk
 
Scala laboratory: Globus. iteration #2
Vasil Remeniuk
 
Testing in Scala. Adform Research
Vasil Remeniuk
 
Scala laboratory. Globus. iteration #1
Vasil Remeniuk
 
Cassandra + Spark + Elk
Vasil Remeniuk
 
Опыт использования Spark, Основано на реальных событиях
Vasil Remeniuk
 
ETL со Spark
Vasil Remeniuk
 

Recently uploaded (20)

PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 

Effective Scala: Programming Patterns

  • 2. The most of the patterns you've got used to in a traditional OO-languages (C++, Java, C#) are just language constructs in a functional languages
  • 3. The key principle behind the most of techniques is functional languages is composition - ability to build assets that can be reused in different contexts unknown at the time they created
  • 5. What if you wanted to add new method for Int? In Java you would write a wrapper class and use it everywhere you want your new Int on steroids. In Scala you would use implicit conversions. object RichInt { implicit def intToRichInt(i: Int) = new RichInt(i) } class RichInt(private val value: Int) { def minutes = value + " minutes" } // Usage example import RichInt._ println(10 minutes) //println(intToRichInt(10).minutes)
  • 6. Pimp My Library ● Simple ● Less boilerplate then ad-hoc conversion ● Can be controlled with scoping
  • 8. Cell is an object behaving closely like a normal variable Implementation details are hidden from end user Scala has two features in possesion helping us to implement such a semi-variable: 1. "First class object" functions var f: Option[() => Int] = Some(() => 1) 2. Syntactic sugar for update and apply x() == x.apply() and x(<arguments>*) = y == x.update(<arguments>*, y)
  • 9. Let's design lazy value using Cell pattern class Lazy[T] { private var v: Option[T] = None private var t: Option[() => T] = None def update(t: => T) { this.t = Some(t _) v = None } def apply() = { if(v.isEmpty) v = Some(t.get()) v.get } } val l = new Lazy[Int] l() = { println("Evaluated"); 1} println ("Before evaluated") println(l()) l() = 2 println(l())
  • 10. Cell actually is ● Simple once again ● Used similar to a variable thanks to syntactic sugar ● Still an object
  • 12. Unified factory import java.util.Date trait Vendor[T] { def vend: T } implicit object DateVendor extends Vendor[Date] { def vend = new Date } object Vendor { def vend[T](implicit vendor: Vendor[T]):T = vendor.vend } val date = Vendor.vend[Date] This guy is like a one man band. Tell him a type you wanna play with and he'll hand you off an instance.
  • 13. Type class ● Extendable through composition ● Abstracts capabilities from data ● Connects different class hierarchies together ● Controlable with scoping
  • 15. OMG, we're in J2EE environment Following dreaded pattern can often be seen in IOC container environment(well at least when it's a bad one) class DBDriver class Bean { private var driver: DBDriver = null def getDriver() = driver def setDriver(driver: DBDriver) { this.driver = driver } } class AnotherBeanFromAnotherParty { private var driver: DBDriver = null def getDriver() = driver def setDriver(driver:DBDriver) { this.driver = driver } } object Bean extends Bean { setDriver(new DBDriver) } object AnotherBeanFromAnotherParty extends AnotherBeanFromAnotherParty { setDriver(new DBDriver) } Here is how we work this around with structural typing def extractDriver(bean: { def getDriver(): DBDriver }): DBDriver = bean.getDriver() extractDriver (Bean) extractDriver(AnotherBeanFromAnotherParty)
  • 16. Structural typing ● Actually a workaround for poorly designed architecture ● A typesafe workaround ● Follows don't repeat yourself
  • 18. ..."Dependency Injection" is a 25-dollar term for a 5-cent concept... Dependency injection means giving an object its instance variables... James Shore
  • 19. What do you need dependency injection for? ● reduces coupling between components ● simplifies configuration of an assembly ○ useful for unit testing
  • 20. IoC containers take a simple, elegant, and useful concept, and make it something you have to study for two days with a 200-page manual Joel Spolsky
  • 21. ● in Scala you don't need any DI framework - forget Spring and Guice ● you make DI with mixins & self-type annotations and no boilerplate
  • 23. What's so cool in Cake pattern? ● It's not a framework, thus any IDE supports it out-of-box ● If a dependency is missing, compiler will immediately let you know about it
  • 25. The brain of an average human is used by only 10% through the lifetime The type system is used by an average programmer by only 10% of its power
  • 26. Phantom types is a simple yet powerful way to use the type system more effectively 2 facts about phantom types: ● never instantiated ● used only to construct other types
  • 27. Let's say, we need a data type to represent the form data extracted from an HTTP request: case class FormData[+T <: Data] (data: Map[String, String]) trait Data trait Validated extends Data trait Unvalidated extends Data Validated and Unvalidated are phantom types
  • 28. trait Form { val readFormData: HttpServletRequest => FormData [Unvalidated] val validate: FormData[Unvalidated] => FormData [Validated] val printFormData: FormData[Validated] => Any } (readFormData andThen validate andThen printFormData) (request) (readFormData andThen printFormData)(request) // FAILS!!!