SlideShare a Scribd company logo
Rewriting Java in Scala ...and Making Your Code Lovely
Relevant About Me New to Scala – Summer 2009 http://www.colinhowe.co.uk http://twitter.com/colinhowe
Format Try to keep this as interactive as possible. Introduce a concept Use the concept on some Java Blue is used to highlight  the essence
Case Classes (1) Provide pattern matching Default toString, equals, hashCode
Case Classes Example - Java @Override public boolean equals(Object obj) { if (!(obj instanceof Point)) { return false; } Point other = (Point)obj; return  other.x == x && other.y == y; } @Override public int hashCode() { return x * 17 + y; } } class Point { private int x; private int y; public Point(int x, int y) { this.x = x; this.y = y; } public String toString() { return "Point(x: " + x + ", y: " + y + ")"; }
Case Classes Example - Scala case  class Point(x : Int, y : Int)
Filter Take a list of X and find only certain X E.g. find all even numbers in a list
Filter Example - Java Predicate evenNumbers = new Predicate() { @Override public boolean evaluate(Object o) { Integer n = (Integer)o; // Assume list contains only integers return  n % 2 == 0 ; } }; CollectionUtils.filter( list , evenNumbers);
Filter Example - Java List<Integer> evens = new LinkedList<Integer>(); for (Integer i :  list ) { if ( i % 2 == 0 ) evens.add(i); }
Filter Example - Scala val evens =  list .filter( _ % 2 == 0 )
Pattern Matching Think switch on steroids result match { case &quot;A&quot; | &quot;B&quot; => println(&quot;A or B!&quot;) case &quot;C&quot; => println(&quot;Just C.&quot;) case e : Exception => println(&quot;Broken: &quot; + e) case _ => println(&quot;Anything else!&quot;) }
Matching Example - Java @Override public boolean equals(Object obj) { if ( !(obj instanceof Point) ) { return false; } Point other = (Point)obj; return  other.x == x && other.y == y ; }
Matching Example - Scala override def equals(o : Any) : Boolean = o match { case  p : Point => p.x == this.x && p.y == this.y case  _  =>  false }
Map Take a list of X and turn it into a list of Y Lists are the same size
Map Example (1) - Java for (int i :  list ) { result.add( i * 2 ); }
Map Example (1) - Scala val result =  list .map( _ * 2 )
Map Example (2) - Java for (int n : list) { List<Integer> factors = new LinkedList<Integer>(); int p = 2; while (p <= n) { if (n % p == 0) { factors.add(p); n /= p; } else { p++; } } result.add(factors); }
Map Example (2) - Scala def factorise(n : Int) : List[Int] = { val factors = scala.collection.mutable.ListBuffer[Int]() var currentValue = n var p = 2 while (p <= currentValue) { if (currentValue % p == 0) { factors += p currentValue = currentValue / p } else { p = p + 1 } } factors.toList }
Map Example (2) - Scala def factorise(n : Int, p : Int) : List[Int] = { if (n == 1) Nil else if (n % p == 0) p :: factorise(n / p, p) else factorise(n, p + 1) } def factorise(n : Int) : List[Int] = factorise(n, 2)
Map Example (2) - Scala def factorise(n : Int, p : Int, factors : List[Int]) : List[Int] = { if (n == 1) factors else if (n % p == 0) factorise(n / p, p, p :: factors) else factorise(n, p + 1, factors) } def factorise(n : Int) : List[Int] = factorise(n, 2, Nil)
Map Example (2) - Scala val result = list.map(factorise)
Fold Take a list of X and turn it into a single Y by combining each element in the list left = do the operation on the left-most element first
Fold Example (1) - Java int total =  0 ; for (int i :  someList ) { total  += i ; }
Fold Example (1) - Scala val sum =  someList .foldLeft( 0 )( _ + _ )
Fold Example (2) - Java int successCount =  0 ; for (Message m :  messages ) { successCount += process(m) }
Fold Example (2) - Scala val successCount = messages.foldLeft( 0 )( _ + process(_) )
Spot Common Constructs Spot re-used constructs Replace with a more functional construct Try to extract out algorithms and data
Common Constructs - Java for (Car car : cars) { if (!groups.containsKey(car.colour)) { groups.put(car.colour, new HashSet<Car>()); } groups.get(car.colour).add(car); }
Common Constructs - Scala def group[T, K](list : List[T], key : (T => K)) : Map[K, Set[T]] = { val groups = scala.collection.mutable.Map[K, Set[T]]() for (t <- list) { if (!groups.contains(key(t))) { groups(key(t)) = Set[T]() } groups(key(t)) = Set[T](t) ++ groups(key(t)) } groups.toMap } val carGroups = group(cars, ((_:car).colour))
Generators For loops with multiple iterators for (x <- 1 to 10; y <- 1 to 20)
Generators Example (1) - Java for (int x = 1; x <= 10; x++) { for (int y = x + 1; y <= 10; y++) { list.add(new Pair(x, y)); } }
Generators Example (1) - Scala val xys =  for (x <- 1 to 10; y <- x + 1 to 10)  yield (x, y)
Generators Example (2) - Java for (Message message :  messages ) { if ( message.isHighPriority() ) { processImmediately(message); } }
Generators Example (2) - Scala for (message <-  messages ; if  message.isHighPriority ) { processImmediately(message) }
Exception Handling Not as forced – no checked exceptions
Exceptions Example - Java final String line; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } // Do stuff with the line
Exceptions Example - Scala val line = reader.readLine() // Do stuff with the line
Exceptions Example - Scala try { val line = reader.readLine() // Do stuff with the line } catch { case e : Exception => println(e) }
Reduce Fold but without a 0 th  value Does not work on the empty list
Reduce Example (1) - Java int currentMax =  someList.get(0) ; for (int i :  someList ) { if (i > currentMax)  { currentMax = i ; } }
Reduce Example (1) - Scala val currentMax =  someList .reduceLeft(0)( max )
Random Tricks Slight break from the format. Covering a few random things that have no proper equivalent in Java.
Releasing Resources withBufferedReader(new File(&quot;readme&quot;)) { reader => reader.readLine } def withBufferedReader(file : File)(op : BufferedReader => Unit) = { val reader = new BufferedReader(new FileReader(file)) try { op(reader) } finally { reader.close() } }
Testing Way more fun in Scala. Make your own DSLs :)
Testing DSL Example def testSimpleAddition { &quot;1 + 1&quot; evaluates 2 &quot;2 + 3 + 4&quot; evaluates 9 } implicit def evaluates(source : String) = new { def evaluates(value : Int) { // Invoke the expression evaluator and check the value } }
Some Guidelines
Some Guidelines Write small functions... …  do pass around functions
Some Guidelines Abstract out algorithms
Some Guidelines Write small classes / traits
Some Guidelines If you see unwanted state... …  you can probably remove it
Some Guidelines Immutability is King
Questions :)
Raffle! Fill in your evaluation forms Prize: free ticket to the Scala Life-off in September!

More Related Content

What's hot (20)

ODP
Effective way to code in Scala
Knoldus Inc.
 
PDF
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
Philip Schwarz
 
PDF
Scala collections
Inphina Technologies
 
ODP
Type Parameterization
Knoldus Inc.
 
PDF
Reasoning about laziness
Johan Tibell
 
PDF
Functional programming with haskell
faradjpour
 
ODP
Collections In Scala
Knoldus Inc.
 
PPT
Functional programming with_scala
Raymond Tay
 
PDF
Beginning Haskell, Dive In, Its Not That Scary!
priort
 
PDF
Haskell for data science
John Cant
 
PDF
Data Structures In Scala
Knoldus Inc.
 
PDF
Monad Transformers - Part 1
Philip Schwarz
 
PDF
Python list
Prof. Dr. K. Adisesha
 
PDF
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
John De Goes
 
PDF
High-Performance Haskell
Johan Tibell
 
PPT
Scala collection
Knoldus Inc.
 
PDF
Scala. Introduction to FP. Monads
Kirill Kozlov
 
PDF
A taste of Functional Programming
Jordan Open Source Association
 
PDF
Fp in scala part 1
Hang Zhao
 
Effective way to code in Scala
Knoldus Inc.
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
Philip Schwarz
 
Scala collections
Inphina Technologies
 
Type Parameterization
Knoldus Inc.
 
Reasoning about laziness
Johan Tibell
 
Functional programming with haskell
faradjpour
 
Collections In Scala
Knoldus Inc.
 
Functional programming with_scala
Raymond Tay
 
Beginning Haskell, Dive In, Its Not That Scary!
priort
 
Haskell for data science
John Cant
 
Data Structures In Scala
Knoldus Inc.
 
Monad Transformers - Part 1
Philip Schwarz
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
John De Goes
 
High-Performance Haskell
Johan Tibell
 
Scala collection
Knoldus Inc.
 
Scala. Introduction to FP. Monads
Kirill Kozlov
 
A taste of Functional Programming
Jordan Open Source Association
 
Fp in scala part 1
Hang Zhao
 

Viewers also liked (20)

PPTX
Scala 2.10.0
Daniel Sobral
 
PDF
Functional Scala I
Mario Gleichmann
 
PDF
Functional Scala II (in practice)
Mario Gleichmann
 
KEY
Scala
guest8996422d
 
KEY
Basic Wicket and Scala
stuq
 
PPTX
Scala 2.10.0 (english version)
Daniel Sobral
 
PPTX
Scala Intro
Alexey (Mr_Mig) Migutsky
 
PDF
Scala - A Scalable Language
Mario Gleichmann
 
KEY
Scala For Java Programmers
Enno Runne
 
PDF
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
PDF
Why Scala Is Taking Over the Big Data World
Dean Wampler
 
PPTX
Purely Functional Data Structures in Scala
Vladimir Kostyukov
 
PPTX
Introduction to Scala
Mohammad Hossein Rimaz
 
PDF
Why Scala?
Alex Payne
 
PDF
Building microservices with Scala, functional domain models and Spring Boot
Chris Richardson
 
PPTX
Advanced Functional Programming in Scala
Patrick Nicolas
 
PDF
Introduction to Scala for Java Developers
Michael Galpin
 
PDF
Streaming Big Data with Spark, Kafka, Cassandra, Akka & Scala (from webinar)
Helena Edelson
 
PDF
Lambda Architecture with Spark, Spark Streaming, Kafka, Cassandra, Akka and S...
Helena Edelson
 
PDF
Introduction to Functional Programming with Scala
pramode_ce
 
Scala 2.10.0
Daniel Sobral
 
Functional Scala I
Mario Gleichmann
 
Functional Scala II (in practice)
Mario Gleichmann
 
Basic Wicket and Scala
stuq
 
Scala 2.10.0 (english version)
Daniel Sobral
 
Scala - A Scalable Language
Mario Gleichmann
 
Scala For Java Programmers
Enno Runne
 
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
Why Scala Is Taking Over the Big Data World
Dean Wampler
 
Purely Functional Data Structures in Scala
Vladimir Kostyukov
 
Introduction to Scala
Mohammad Hossein Rimaz
 
Why Scala?
Alex Payne
 
Building microservices with Scala, functional domain models and Spring Boot
Chris Richardson
 
Advanced Functional Programming in Scala
Patrick Nicolas
 
Introduction to Scala for Java Developers
Michael Galpin
 
Streaming Big Data with Spark, Kafka, Cassandra, Akka & Scala (from webinar)
Helena Edelson
 
Lambda Architecture with Spark, Spark Streaming, Kafka, Cassandra, Akka and S...
Helena Edelson
 
Introduction to Functional Programming with Scala
pramode_ce
 
Ad

Similar to Rewriting Java In Scala (20)

PPT
Scala Talk at FOSDEM 2009
Martin Odersky
 
PPT
Scala presentationjune112011
PrasannaKumar Sathyanarayanan
 
PPT
JBUG 11 - Scala For Java Programmers
Tikal Knowledge
 
PPTX
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Matthew Farwell
 
PPTX
A Brief Intro to Scala
Tim Underwood
 
PDF
Workshop Scala
Bert Van Vreckem
 
PPT
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
PDF
From Java to Scala - advantages and possible risks
SeniorDevOnly
 
PPSX
Scala @ TomTom
Eric Bowman
 
PPT
Scala Language Intro - Inspired by the Love Game
Antony Stubbs
 
PPTX
Scala en
Fero Kocun
 
PPT
An introduction to scala
Mohsen Zainalpour
 
PPTX
Practically Functional
djspiewak
 
PDF
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
PDF
Scala
Sven Efftinge
 
PDF
Scala or functional programming from a python developer's perspective
gabalese
 
ODP
Scala ntnu
Alf Kristian Støyle
 
PPT
Scala introduction
Yardena Meymann
 
ODP
Scala introduction
Alf Kristian Støyle
 
PDF
Frp2016 3
Kirill Kozlov
 
Scala Talk at FOSDEM 2009
Martin Odersky
 
Scala presentationjune112011
PrasannaKumar Sathyanarayanan
 
JBUG 11 - Scala For Java Programmers
Tikal Knowledge
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Matthew Farwell
 
A Brief Intro to Scala
Tim Underwood
 
Workshop Scala
Bert Van Vreckem
 
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
From Java to Scala - advantages and possible risks
SeniorDevOnly
 
Scala @ TomTom
Eric Bowman
 
Scala Language Intro - Inspired by the Love Game
Antony Stubbs
 
Scala en
Fero Kocun
 
An introduction to scala
Mohsen Zainalpour
 
Practically Functional
djspiewak
 
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
Scala or functional programming from a python developer's perspective
gabalese
 
Scala introduction
Yardena Meymann
 
Scala introduction
Alf Kristian Støyle
 
Frp2016 3
Kirill Kozlov
 
Ad

More from Skills Matter (20)

PDF
5 things cucumber is bad at by Richard Lawrence
Skills Matter
 
ODP
Patterns for slick database applications
Skills Matter
 
PDF
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
Skills Matter
 
ODP
Oscar reiken jr on our success at manheim
Skills Matter
 
ODP
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Skills Matter
 
PDF
Cukeup nyc ian dees on elixir, erlang, and cucumberl
Skills Matter
 
PDF
Cukeup nyc peter bell on getting started with cucumber.js
Skills Matter
 
PDF
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Skills Matter
 
ODP
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Skills Matter
 
ODP
Progressive f# tutorials nyc don syme on keynote f# in the open source world
Skills Matter
 
PDF
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Skills Matter
 
PPTX
Dmitry mozorov on code quotations code as-data for f#
Skills Matter
 
PDF
A poet's guide_to_acceptance_testing
Skills Matter
 
PDF
Russ miles-cloudfoundry-deep-dive
Skills Matter
 
KEY
Serendipity-neo4j
Skills Matter
 
PDF
Simon Peyton Jones: Managing parallelism
Skills Matter
 
PDF
Plug 20110217
Skills Matter
 
PDF
Lug presentation
Skills Matter
 
PPT
I went to_a_communications_workshop_and_they_t
Skills Matter
 
PDF
Plug saiku
Skills Matter
 
5 things cucumber is bad at by Richard Lawrence
Skills Matter
 
Patterns for slick database applications
Skills Matter
 
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
Skills Matter
 
Oscar reiken jr on our success at manheim
Skills Matter
 
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Skills Matter
 
Cukeup nyc ian dees on elixir, erlang, and cucumberl
Skills Matter
 
Cukeup nyc peter bell on getting started with cucumber.js
Skills Matter
 
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Skills Matter
 
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Skills Matter
 
Progressive f# tutorials nyc don syme on keynote f# in the open source world
Skills Matter
 
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Skills Matter
 
Dmitry mozorov on code quotations code as-data for f#
Skills Matter
 
A poet's guide_to_acceptance_testing
Skills Matter
 
Russ miles-cloudfoundry-deep-dive
Skills Matter
 
Serendipity-neo4j
Skills Matter
 
Simon Peyton Jones: Managing parallelism
Skills Matter
 
Plug 20110217
Skills Matter
 
Lug presentation
Skills Matter
 
I went to_a_communications_workshop_and_they_t
Skills Matter
 
Plug saiku
Skills Matter
 

Recently uploaded (20)

PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Digital Circuits, important subject in CS
contactparinay1
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 

Rewriting Java In Scala

  • 1. Rewriting Java in Scala ...and Making Your Code Lovely
  • 2. Relevant About Me New to Scala – Summer 2009 http://www.colinhowe.co.uk http://twitter.com/colinhowe
  • 3. Format Try to keep this as interactive as possible. Introduce a concept Use the concept on some Java Blue is used to highlight the essence
  • 4. Case Classes (1) Provide pattern matching Default toString, equals, hashCode
  • 5. Case Classes Example - Java @Override public boolean equals(Object obj) { if (!(obj instanceof Point)) { return false; } Point other = (Point)obj; return other.x == x && other.y == y; } @Override public int hashCode() { return x * 17 + y; } } class Point { private int x; private int y; public Point(int x, int y) { this.x = x; this.y = y; } public String toString() { return &quot;Point(x: &quot; + x + &quot;, y: &quot; + y + &quot;)&quot;; }
  • 6. Case Classes Example - Scala case class Point(x : Int, y : Int)
  • 7. Filter Take a list of X and find only certain X E.g. find all even numbers in a list
  • 8. Filter Example - Java Predicate evenNumbers = new Predicate() { @Override public boolean evaluate(Object o) { Integer n = (Integer)o; // Assume list contains only integers return n % 2 == 0 ; } }; CollectionUtils.filter( list , evenNumbers);
  • 9. Filter Example - Java List<Integer> evens = new LinkedList<Integer>(); for (Integer i : list ) { if ( i % 2 == 0 ) evens.add(i); }
  • 10. Filter Example - Scala val evens = list .filter( _ % 2 == 0 )
  • 11. Pattern Matching Think switch on steroids result match { case &quot;A&quot; | &quot;B&quot; => println(&quot;A or B!&quot;) case &quot;C&quot; => println(&quot;Just C.&quot;) case e : Exception => println(&quot;Broken: &quot; + e) case _ => println(&quot;Anything else!&quot;) }
  • 12. Matching Example - Java @Override public boolean equals(Object obj) { if ( !(obj instanceof Point) ) { return false; } Point other = (Point)obj; return other.x == x && other.y == y ; }
  • 13. Matching Example - Scala override def equals(o : Any) : Boolean = o match { case p : Point => p.x == this.x && p.y == this.y case _ => false }
  • 14. Map Take a list of X and turn it into a list of Y Lists are the same size
  • 15. Map Example (1) - Java for (int i : list ) { result.add( i * 2 ); }
  • 16. Map Example (1) - Scala val result = list .map( _ * 2 )
  • 17. Map Example (2) - Java for (int n : list) { List<Integer> factors = new LinkedList<Integer>(); int p = 2; while (p <= n) { if (n % p == 0) { factors.add(p); n /= p; } else { p++; } } result.add(factors); }
  • 18. Map Example (2) - Scala def factorise(n : Int) : List[Int] = { val factors = scala.collection.mutable.ListBuffer[Int]() var currentValue = n var p = 2 while (p <= currentValue) { if (currentValue % p == 0) { factors += p currentValue = currentValue / p } else { p = p + 1 } } factors.toList }
  • 19. Map Example (2) - Scala def factorise(n : Int, p : Int) : List[Int] = { if (n == 1) Nil else if (n % p == 0) p :: factorise(n / p, p) else factorise(n, p + 1) } def factorise(n : Int) : List[Int] = factorise(n, 2)
  • 20. Map Example (2) - Scala def factorise(n : Int, p : Int, factors : List[Int]) : List[Int] = { if (n == 1) factors else if (n % p == 0) factorise(n / p, p, p :: factors) else factorise(n, p + 1, factors) } def factorise(n : Int) : List[Int] = factorise(n, 2, Nil)
  • 21. Map Example (2) - Scala val result = list.map(factorise)
  • 22. Fold Take a list of X and turn it into a single Y by combining each element in the list left = do the operation on the left-most element first
  • 23. Fold Example (1) - Java int total = 0 ; for (int i : someList ) { total += i ; }
  • 24. Fold Example (1) - Scala val sum = someList .foldLeft( 0 )( _ + _ )
  • 25. Fold Example (2) - Java int successCount = 0 ; for (Message m : messages ) { successCount += process(m) }
  • 26. Fold Example (2) - Scala val successCount = messages.foldLeft( 0 )( _ + process(_) )
  • 27. Spot Common Constructs Spot re-used constructs Replace with a more functional construct Try to extract out algorithms and data
  • 28. Common Constructs - Java for (Car car : cars) { if (!groups.containsKey(car.colour)) { groups.put(car.colour, new HashSet<Car>()); } groups.get(car.colour).add(car); }
  • 29. Common Constructs - Scala def group[T, K](list : List[T], key : (T => K)) : Map[K, Set[T]] = { val groups = scala.collection.mutable.Map[K, Set[T]]() for (t <- list) { if (!groups.contains(key(t))) { groups(key(t)) = Set[T]() } groups(key(t)) = Set[T](t) ++ groups(key(t)) } groups.toMap } val carGroups = group(cars, ((_:car).colour))
  • 30. Generators For loops with multiple iterators for (x <- 1 to 10; y <- 1 to 20)
  • 31. Generators Example (1) - Java for (int x = 1; x <= 10; x++) { for (int y = x + 1; y <= 10; y++) { list.add(new Pair(x, y)); } }
  • 32. Generators Example (1) - Scala val xys = for (x <- 1 to 10; y <- x + 1 to 10) yield (x, y)
  • 33. Generators Example (2) - Java for (Message message : messages ) { if ( message.isHighPriority() ) { processImmediately(message); } }
  • 34. Generators Example (2) - Scala for (message <- messages ; if message.isHighPriority ) { processImmediately(message) }
  • 35. Exception Handling Not as forced – no checked exceptions
  • 36. Exceptions Example - Java final String line; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } // Do stuff with the line
  • 37. Exceptions Example - Scala val line = reader.readLine() // Do stuff with the line
  • 38. Exceptions Example - Scala try { val line = reader.readLine() // Do stuff with the line } catch { case e : Exception => println(e) }
  • 39. Reduce Fold but without a 0 th value Does not work on the empty list
  • 40. Reduce Example (1) - Java int currentMax = someList.get(0) ; for (int i : someList ) { if (i > currentMax) { currentMax = i ; } }
  • 41. Reduce Example (1) - Scala val currentMax = someList .reduceLeft(0)( max )
  • 42. Random Tricks Slight break from the format. Covering a few random things that have no proper equivalent in Java.
  • 43. Releasing Resources withBufferedReader(new File(&quot;readme&quot;)) { reader => reader.readLine } def withBufferedReader(file : File)(op : BufferedReader => Unit) = { val reader = new BufferedReader(new FileReader(file)) try { op(reader) } finally { reader.close() } }
  • 44. Testing Way more fun in Scala. Make your own DSLs :)
  • 45. Testing DSL Example def testSimpleAddition { &quot;1 + 1&quot; evaluates 2 &quot;2 + 3 + 4&quot; evaluates 9 } implicit def evaluates(source : String) = new { def evaluates(value : Int) { // Invoke the expression evaluator and check the value } }
  • 47. Some Guidelines Write small functions... … do pass around functions
  • 48. Some Guidelines Abstract out algorithms
  • 49. Some Guidelines Write small classes / traits
  • 50. Some Guidelines If you see unwanted state... … you can probably remove it
  • 53. Raffle! Fill in your evaluation forms Prize: free ticket to the Scala Life-off in September!

Editor's Notes

  • #13: I like this. You&apos;re not testing that you can call your own API correctly... you&apos;re testing that some expression evaluates to some value. It&apos;s clear what the test is checking and it&apos;s easy to check the test is correct (assuming the internal calls are correct).
  • #14: I like this. You&apos;re not testing that you can call your own API correctly... you&apos;re testing that some expression evaluates to some value. It&apos;s clear what the test is checking and it&apos;s easy to check the test is correct (assuming the internal calls are correct).
  • #46: I like this. You&apos;re not testing that you can call your own API correctly... you&apos;re testing that some expression evaluates to some value. It&apos;s clear what the test is checking and it&apos;s easy to check the test is correct (assuming the internal calls are correct).