SlideShare une entreprise Scribd logo
1  sur  53
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 ,[object Object],[object Object],[object Object],[object Object]
Case Classes (1) ,[object Object],[object Object]
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!

Contenu connexe

Tendances

Effective way to code in Scala
Effective way to code in ScalaEffective way to code in Scala
Effective way to code in ScalaKnoldus Inc.
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...Philip Schwarz
 
Type Parameterization
Type ParameterizationType Parameterization
Type ParameterizationKnoldus Inc.
 
Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about lazinessJohan Tibell
 
Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskellfaradjpour
 
Collections In Scala
Collections In ScalaCollections In Scala
Collections In ScalaKnoldus Inc.
 
Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scalaRaymond Tay
 
Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!priort
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data scienceJohn Cant
 
Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In ScalaKnoldus Inc.
 
Monad Transformers - Part 1
Monad Transformers - Part 1Monad Transformers - Part 1
Monad Transformers - Part 1Philip Schwarz
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsJohn De Goes
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance HaskellJohan Tibell
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsKirill Kozlov
 
Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1Hang Zhao
 

Tendances (20)

Effective way to code in Scala
Effective way to code in ScalaEffective way to code in Scala
Effective way to code in Scala
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
 
Scala collections
Scala collectionsScala collections
Scala collections
 
Type Parameterization
Type ParameterizationType Parameterization
Type Parameterization
 
Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about laziness
 
Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskell
 
Collections In Scala
Collections In ScalaCollections In Scala
Collections In Scala
 
Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scala
 
Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data science
 
Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In Scala
 
Monad Transformers - Part 1
Monad Transformers - Part 1Monad Transformers - Part 1
Monad Transformers - Part 1
 
Python list
Python listPython list
Python list
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
 
Scala collection
Scala collectionScala collection
Scala collection
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. Monads
 
Lec4
Lec4Lec4
Lec4
 
A taste of Functional Programming
A taste of Functional ProgrammingA taste of Functional Programming
A taste of Functional Programming
 
Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1
 

En vedette

Functional Scala II (in practice)
Functional Scala II (in practice)Functional Scala II (in practice)
Functional Scala II (in practice)Mario Gleichmann
 
Basic Wicket and Scala
Basic Wicket and ScalaBasic Wicket and Scala
Basic Wicket and Scalastuq
 
Scala 2.10.0 (english version)
Scala 2.10.0 (english version)Scala 2.10.0 (english version)
Scala 2.10.0 (english version)Daniel Sobral
 
Scala - A Scalable Language
Scala - A Scalable LanguageScala - A Scalable Language
Scala - A Scalable LanguageMario Gleichmann
 
Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java ProgrammersEnno Runne
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Why Scala Is Taking Over the Big Data World
Why Scala Is Taking Over the Big Data WorldWhy Scala Is Taking Over the Big Data World
Why Scala Is Taking Over the Big Data WorldDean Wampler
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaVladimir Kostyukov
 
Building microservices with Scala, functional domain models and Spring Boot
Building microservices with Scala, functional domain models and Spring BootBuilding microservices with Scala, functional domain models and Spring Boot
Building microservices with Scala, functional domain models and Spring BootChris Richardson
 
Advanced Functional Programming in Scala
Advanced Functional Programming in ScalaAdvanced Functional Programming in Scala
Advanced Functional Programming in ScalaPatrick Nicolas
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java DevelopersMichael Galpin
 
Streaming Big Data with Spark, Kafka, Cassandra, Akka & Scala (from webinar)
Streaming Big Data with Spark, Kafka, Cassandra, Akka & Scala (from webinar)Streaming Big Data with Spark, Kafka, Cassandra, Akka & Scala (from webinar)
Streaming Big Data with Spark, Kafka, Cassandra, Akka & Scala (from webinar)Helena Edelson
 
Lambda Architecture with Spark, Spark Streaming, Kafka, Cassandra, Akka and S...
Lambda Architecture with Spark, Spark Streaming, Kafka, Cassandra, Akka and S...Lambda Architecture with Spark, Spark Streaming, Kafka, Cassandra, Akka and S...
Lambda Architecture with Spark, Spark Streaming, Kafka, Cassandra, Akka and S...Helena Edelson
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 

En vedette (20)

Scala 2.10.0
Scala 2.10.0Scala 2.10.0
Scala 2.10.0
 
Functional Scala I
Functional Scala IFunctional Scala I
Functional Scala I
 
Functional Scala II (in practice)
Functional Scala II (in practice)Functional Scala II (in practice)
Functional Scala II (in practice)
 
Scala
ScalaScala
Scala
 
Basic Wicket and Scala
Basic Wicket and ScalaBasic Wicket and Scala
Basic Wicket and Scala
 
Scala 2.10.0 (english version)
Scala 2.10.0 (english version)Scala 2.10.0 (english version)
Scala 2.10.0 (english version)
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Scala - A Scalable Language
Scala - A Scalable LanguageScala - A Scalable Language
Scala - A Scalable Language
 
Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java Programmers
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Why Scala Is Taking Over the Big Data World
Why Scala Is Taking Over the Big Data WorldWhy Scala Is Taking Over the Big Data World
Why Scala Is Taking Over the Big Data World
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Why Scala?
Why Scala?Why Scala?
Why Scala?
 
Building microservices with Scala, functional domain models and Spring Boot
Building microservices with Scala, functional domain models and Spring BootBuilding microservices with Scala, functional domain models and Spring Boot
Building microservices with Scala, functional domain models and Spring Boot
 
Advanced Functional Programming in Scala
Advanced Functional Programming in ScalaAdvanced Functional Programming in Scala
Advanced Functional Programming in Scala
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java Developers
 
Streaming Big Data with Spark, Kafka, Cassandra, Akka & Scala (from webinar)
Streaming Big Data with Spark, Kafka, Cassandra, Akka & Scala (from webinar)Streaming Big Data with Spark, Kafka, Cassandra, Akka & Scala (from webinar)
Streaming Big Data with Spark, Kafka, Cassandra, Akka & Scala (from webinar)
 
Lambda Architecture with Spark, Spark Streaming, Kafka, Cassandra, Akka and S...
Lambda Architecture with Spark, Spark Streaming, Kafka, Cassandra, Akka and S...Lambda Architecture with Spark, Spark Streaming, Kafka, Cassandra, Akka and S...
Lambda Architecture with Spark, Spark Streaming, Kafka, Cassandra, Akka and S...
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 

Similaire à Rewriting Java In Scala

Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009David Pollak
 
JBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersJBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersTikal Knowledge
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
1.2 Scala Basics
1.2 Scala Basics1.2 Scala Basics
1.2 Scala Basicsretronym
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
Scala as a Declarative Language
Scala as a Declarative LanguageScala as a Declarative Language
Scala as a Declarative Languagevsssuresh
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxAbhishek Tirkey
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxGauravPandey43518
 
Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02Nguyen Tuan
 

Similaire à Rewriting Java In Scala (20)

SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Scala @ TomTom
Scala @ TomTomScala @ TomTom
Scala @ TomTom
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009
 
JBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersJBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java Programmers
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
Lec2
Lec2Lec2
Lec2
 
1.2 Scala Basics
1.2 Scala Basics1.2 Scala Basics
1.2 Scala Basics
 
Scala basic
Scala basicScala basic
Scala basic
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Scala en
Scala enScala en
Scala en
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Scala as a Declarative Language
Scala as a Declarative LanguageScala as a Declarative Language
Scala as a Declarative Language
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Jeop game-final-review
Jeop game-final-reviewJeop game-final-review
Jeop game-final-review
 
Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02
 

Plus de Skills Matter

5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard Lawrence5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard LawrenceSkills Matter
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applicationsSkills Matter
 
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvmScala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvmSkills Matter
 
Oscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheimOscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheimSkills Matter
 
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...Skills Matter
 
Cukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberlCukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberlSkills Matter
 
Cukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.jsCukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.jsSkills Matter
 
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
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...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
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
Progressive f# tutorials nyc don syme on keynote f# in the open source worldProgressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source worldSkills Matter
 
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
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#
Dmitry mozorov on code quotations code as-data for f#Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#Skills Matter
 
A poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testingA poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testingSkills Matter
 
Russ miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-diveRuss miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-diveSkills Matter
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSkills Matter
 
I went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_tI went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_tSkills Matter
 

Plus de Skills Matter (20)

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

Dernier

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 

Dernier (20)

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 

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.
  • 4.
  • 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!

Notes de l'éditeur

  1. 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).
  2. 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).
  3. 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).