SlideShare una empresa de Scribd logo
1 de 45
Descargar para leer sin conexión
Scala Collections : Java 8 on Steroids
François Garillot
Twitter : @huitseeker
francois.garillot@typesafe.com
1
What this talk is
2
What this talk is
A look at Java 8 gives you
2-a
What this talk is
A look at Java 8 gives you
... and what it doesn’t
2-b
What this talk is
A look at Java 8 gives you
... and what it doesn’t
A look at Scala collections
2-c
What this talk is
A look at Java 8 gives you
... and what it doesn’t
A look at Scala collections
A look at the why and how of collections
2-d
What this talk is not
3
What this talk is not
New stuff
3-a
What this talk is not
New stuff
Rocket Science
3-b
What this talk is not
New stuff
Rocket Science
Polemic
3-c
What I’m hoping for
4
What I’m hoping for
A discussion
4-a
What I’m hoping for
A discussion
Making things a tad more clear
4-b
What I’m hoping for
A discussion
Making things a tad more clear
... or just less overlooked ?
4-c
What I’m hoping for
A discussion
Making things a tad more clear
... or just less overlooked ?
Not too boring
4-d
What (functional, new things) you can do with Java 8
Lambda-expressions
(String first, String second) ->
Integer.compare(first.length(), second.length)
Functional Interfaces
Runnable r = () -> System.out.println("I am Runnable!");
Method references
button.setOnAction(System.out::println);
Constructor references
List<String> labels = ... ;
Stream<Button> buttonsStream = labels.stream().map(Button::new);
Buttons[] buttonsArray = labels.stream().toArray(Button::new);
int[]::new;
5
The devil is in the details
Optional<T>, Optional.of(), Optional.ofNullable(), Optional.empty()
Default methods in interfaces.
list.forEach(System.out::println)
... beware: SuperClasses win, Interfaces clash. ... And the standard library was not
entirely rewritten (Path/Paths)
Important topics : variable capture in closures, parallel execution.
int[] counter = new int[1];
button.setOnAction(event -> counter[0]++);
6
And also, Streams
Any Collection has a stream()
Stream.of() with a vararg, an array
filter, map, flatMap, as well as plumbing: split, concat, limit
Lazy processing, parallel() processing (you enforce statelessness)
terminal reductions, e.g. reduce
collector:
HashSet<String> result =
stream.collect(HashSet::new, HashSet::add, HashSet::addAll)
Collector implementations (toList, toMap, ...)
counting, maxBy, groupinBy, mapping, ...
Beware: think about reuse.
7
Interlude
8
Interlude
Does that make Java a functional programming language ?
8-a
Interlude
Does that make Java a functional programming language ?
First class functions
8-b
Interlude
Does that make Java a functional programming language ?
First class functions
Technicalities
8-c
Interlude
Does that make Java a functional programming language ?
First class functions
Technicalities
Does that make Java a Scala competitor ?
8-d
Interlude
Does that make Java a functional programming language ?
First class functions
Technicalities
Does that make Java a Scala competitor ?
Scala has never had a feature poverty problem.
8-e
What you can’t do with Java 8 (yet)
1. Case classes
2. Pattern matching
3. Tail call elimination
4. Scoped access
5. Lazy keyword
6. Traits (well-scoped)
7. Rich Imports (local, aliased)
8. Macros
9. Backend (Miguel Garcia)
10. Specialization (Vlad Ureche)
11. Value classes
12. Implicits
13. Cake !
9
Collections
The signatures of map
Type classes & implicits
Design goals
10
The signatures of map
11
The signatures of map
def map[B](f: (A) ⇒ B) : Map[B]
11-a
The signatures of map
def map[B](f: (A) ⇒ B) : Map[B]
But ... Type Constructor Polymorphism
11-b
The signatures of map
def map[B](f: (A) ⇒ B) : Map[B]
But ... Type Constructor Polymorphism
trait TraversableLike[+Elem, +Coll[+x]] {
def map[NewElem](f: Elem ⇒ NewElem): Coll[NewElem]
def filter(p: Elem ⇒ Boolean): Coll[Elem]
}
11-c
The signatures of map
def map[B](f: (A) ⇒ B) : Map[B]
But ... Type Constructor Polymorphism
trait TraversableLike[+Elem, +Coll[+x]] {
def map[NewElem](f: Elem ⇒ NewElem): Coll[NewElem]
def filter(p: Elem ⇒ Boolean): Coll[Elem]
}
The idea that, whatever map needs, it will always deal with:
11-d
The signatures of map
def map[B](f: (A) ⇒ B) : Map[B]
But ... Type Constructor Polymorphism
trait TraversableLike[+Elem, +Coll[+x]] {
def map[NewElem](f: Elem ⇒ NewElem): Coll[NewElem]
def filter(p: Elem ⇒ Boolean): Coll[Elem]
}
The idea that, whatever map needs, it will always deal with:
(Collection[Elements],
Elements ⇒ OtherElements,
Collection[OtherElements])
11-e
The signatures of map
12
The signatures of map
12-a
The signatures of map
trait TraversableLike[+Elem, +Repr] {
protected[this] def newBuilder: Builder[Elem, Repr] // deferred
def foreach[U](f: Elem ⇒ U) // deferred
def filter(p: Elem ⇒ Boolean): Repr = {
val b = newBuilder
foreach { elem <- if (p(elem)) b += elem }
b.result
}
}
class Builder[-Elem, +To] {
def +=(elem: Elem): this.type = . . .
def result(): To = . . .
def clear() = . . .
def mapResult[NewTo](f: To ⇒ NewTo): Builder[Elem, NewTo] = . . .
}
12-b
The signatures of map
trait TraversableLike[+Elem, +Repr] {
protected[this] def newBuilder: Builder[Elem, Repr] // deferred
def foreach[U](f: Elem ⇒ U) // deferred
def filter(p: Elem ⇒ Boolean): Repr = {
val b = newBuilder
foreach { elem <- if (p(elem)) b += elem }
b.result
}
}
class Builder[-Elem, +To] {
def +=(elem: Elem): this.type = . . .
def result(): To = . . .
def clear() = . . .
def mapResult[NewTo](f: To ⇒ NewTo): Builder[Elem, NewTo] = . . .
}
Why do we care ? Extensibility.
12-c
The signatures of map (cont’d)
13
The signatures of map (cont’d)
13-a
The signatures of map (cont’d)
def map[B, That](f: ((A,B)) ⇒ B)
(implicit bf:CanBuildFrom[Map[A,B], B, That]):That
13-b
The signatures of map (cont’d)
def map[B, That](f: ((A,B)) ⇒ B)
(implicit bf:CanBuildFrom[Map[A,B], B, That]):That
Why ?
13-c
The signatures of map (cont’d)
def map[B, That](f: ((A,B)) ⇒ B)
(implicit bf:CanBuildFrom[Map[A,B], B, That]):That
Why ?
Dealing with (Bitset, Int, BitSet) and
(Bitset, String, Set[String])
13-d
The signatures of map (cont’d)
def map[B, That](f: ((A,B)) ⇒ B)
(implicit bf:CanBuildFrom[Map[A,B], B, That]):That
Why ?
Dealing with (Bitset, Int, BitSet) and
(Bitset, String, Set[String])
Dealing with (Map[A, B], (A, B)) ⇒ (B, A), Map[B, A]) and
(Map[A, B], (A, B)) ⇒ T, Iterable[T])
13-e
With Implicits
trait CanBuildFrom[-Collection, -NewElem, +Result] {
def apply(from: Collection): Builder[NewElem, Result]
}
trait TraversableLike[+A, +Repr] {
def repr: Repr = . . .
def foreach[U](f: A ⇒ U): Unit = . . .
def map[B, To](f: A ⇒ B)(implicit cbf: CanBuildFrom[Repr, B, To]): To = {
val b = cbf(repr) // get the builder from the CanBuildFrom instance
for (x <- this) b += f(x) // transform element and add
b.result
}
}
14
trait SetLike[+A, +Repr] extends TraversableLike[A, Repr] { }
trait BitSetLike[+This <: BitSetLike[This] with Set[Int]]
extends SetLike[Int, This] {}
trait Traversable[+A] extends TraversableLike[A, Traversable[A]]
trait Set[+A] extends Traversable[A] with SetLike[A, Set[A]]
class BitSet extends Set[Int] with BitSetLike[BitSet]
object Set {
implicit def canBuildFromSet[B] = new CanBuildFrom[Set[_], B, Set[B]] {
def apply(from: Set[_]) = . . .
}
}
object BitSet {
implicit val canBuildFromBitSet = new CanBuildFrom[BitSet, Int, BitSet] {
def apply(from: BitSet) = . . .
}
}
15
Conclusion
A word about design.
16

Más contenido relacionado

La actualidad más candente

Java collections
Java collectionsJava collections
Java collections
Amar Kutwal
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-library
Hariz Mustafa
 
Java Collections
Java CollectionsJava Collections
Java Collections
parag
 

La actualidad más candente (19)

Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
java collections
java collectionsjava collections
java collections
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 
Collections Java e Google Collections
Collections Java e Google CollectionsCollections Java e Google Collections
Collections Java e Google Collections
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Java collections
Java collectionsJava collections
Java collections
 
07 java collection
07 java collection07 java collection
07 java collection
 
Generics
GenericsGenerics
Generics
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-library
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 

Similar a Scala Collections : Java 8 on Steroids

Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
famous placement papers
famous placement papersfamous placement papers
famous placement papers
Ramanujam Ramu
 

Similar a Scala Collections : Java 8 on Steroids (20)

Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...
 
Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...
 
Taking your side effects aside
Taking your side effects asideTaking your side effects aside
Taking your side effects aside
 
Talk - Query monad
Talk - Query monad Talk - Query monad
Talk - Query monad
 
Scala.io
Scala.ioScala.io
Scala.io
 
Generic Functional Programming with Type Classes
Generic Functional Programming with Type ClassesGeneric Functional Programming with Type Classes
Generic Functional Programming with Type Classes
 
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
 
JSDC 2014 - functional java script, why or why not
JSDC 2014 - functional java script, why or why notJSDC 2014 - functional java script, why or why not
JSDC 2014 - functional java script, why or why not
 
Contravariant functors in scala
Contravariant functors in scalaContravariant functors in scala
Contravariant functors in scala
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And Monad
 
Running Free with the Monads
Running Free with the MonadsRunning Free with the Monads
Running Free with the Monads
 
Building a Functional Stream in Scala
Building a Functional Stream in ScalaBuilding a Functional Stream in Scala
Building a Functional Stream in Scala
 
Developing High Performance Application with Aerospike & Go
Developing High Performance Application with Aerospike & GoDeveloping High Performance Application with Aerospike & Go
Developing High Performance Application with Aerospike & Go
 
Kyo - Functional Scala 2023.pdf
Kyo - Functional Scala 2023.pdfKyo - Functional Scala 2023.pdf
Kyo - Functional Scala 2023.pdf
 
famous placement papers
famous placement papersfamous placement papers
famous placement papers
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Revision1 C programming
Revision1 C programmingRevision1 C programming
Revision1 C programming
 

Más de François Garillot

Mobility insights at Swisscom - Understanding collective mobility in Switzerland
Mobility insights at Swisscom - Understanding collective mobility in SwitzerlandMobility insights at Swisscom - Understanding collective mobility in Switzerland
Mobility insights at Swisscom - Understanding collective mobility in Switzerland
François Garillot
 

Más de François Garillot (8)

Growing Your Types Without Growing Your Workload
Growing Your Types Without Growing Your WorkloadGrowing Your Types Without Growing Your Workload
Growing Your Types Without Growing Your Workload
 
Deep learning on a mixed cluster with deeplearning4j and spark
Deep learning on a mixed cluster with deeplearning4j and sparkDeep learning on a mixed cluster with deeplearning4j and spark
Deep learning on a mixed cluster with deeplearning4j and spark
 
Mobility insights at Swisscom - Understanding collective mobility in Switzerland
Mobility insights at Swisscom - Understanding collective mobility in SwitzerlandMobility insights at Swisscom - Understanding collective mobility in Switzerland
Mobility insights at Swisscom - Understanding collective mobility in Switzerland
 
Delivering near real time mobility insights at swisscom
Delivering near real time mobility insights at swisscomDelivering near real time mobility insights at swisscom
Delivering near real time mobility insights at swisscom
 
Spark Streaming : Dealing with State
Spark Streaming : Dealing with StateSpark Streaming : Dealing with State
Spark Streaming : Dealing with State
 
A Gentle Introduction to Locality Sensitive Hashing with Apache Spark
A Gentle Introduction to Locality Sensitive Hashing with Apache SparkA Gentle Introduction to Locality Sensitive Hashing with Apache Spark
A Gentle Introduction to Locality Sensitive Hashing with Apache Spark
 
Ramping up your Devops Fu for Big Data developers
Ramping up your Devops Fu for Big Data developersRamping up your Devops Fu for Big Data developers
Ramping up your Devops Fu for Big Data developers
 
Diving In The Deep End Of The Big Data Pool
Diving In The Deep End Of The Big Data PoolDiving In The Deep End Of The Big Data Pool
Diving In The Deep End Of The Big Data Pool
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Porella : features, morphology, anatomy, reproduction etc.
Porella : features, morphology, anatomy, reproduction etc.Porella : features, morphology, anatomy, reproduction etc.
Porella : features, morphology, anatomy, reproduction etc.
Silpa
 
Human genetics..........................pptx
Human genetics..........................pptxHuman genetics..........................pptx
Human genetics..........................pptx
Silpa
 
POGONATUM : morphology, anatomy, reproduction etc.
POGONATUM : morphology, anatomy, reproduction etc.POGONATUM : morphology, anatomy, reproduction etc.
POGONATUM : morphology, anatomy, reproduction etc.
Silpa
 
Biogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune Waterworlds
Biogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune WaterworldsBiogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune Waterworlds
Biogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune Waterworlds
Sérgio Sacani
 

Último (20)

Velocity and Acceleration PowerPoint.ppt
Velocity and Acceleration PowerPoint.pptVelocity and Acceleration PowerPoint.ppt
Velocity and Acceleration PowerPoint.ppt
 
Dr. E. Muralinath_ Blood indices_clinical aspects
Dr. E. Muralinath_ Blood indices_clinical  aspectsDr. E. Muralinath_ Blood indices_clinical  aspects
Dr. E. Muralinath_ Blood indices_clinical aspects
 
PSYCHOSOCIAL NEEDS. in nursing II sem pptx
PSYCHOSOCIAL NEEDS. in nursing II sem pptxPSYCHOSOCIAL NEEDS. in nursing II sem pptx
PSYCHOSOCIAL NEEDS. in nursing II sem pptx
 
GBSN - Microbiology (Unit 2)
GBSN - Microbiology (Unit 2)GBSN - Microbiology (Unit 2)
GBSN - Microbiology (Unit 2)
 
Stages in the normal growth curve
Stages in the normal growth curveStages in the normal growth curve
Stages in the normal growth curve
 
Bhiwandi Bhiwandi ❤CALL GIRL 7870993772 ❤CALL GIRLS ESCORT SERVICE In Bhiwan...
Bhiwandi Bhiwandi ❤CALL GIRL 7870993772 ❤CALL GIRLS  ESCORT SERVICE In Bhiwan...Bhiwandi Bhiwandi ❤CALL GIRL 7870993772 ❤CALL GIRLS  ESCORT SERVICE In Bhiwan...
Bhiwandi Bhiwandi ❤CALL GIRL 7870993772 ❤CALL GIRLS ESCORT SERVICE In Bhiwan...
 
Zoology 5th semester notes( Sumit_yadav).pdf
Zoology 5th semester notes( Sumit_yadav).pdfZoology 5th semester notes( Sumit_yadav).pdf
Zoology 5th semester notes( Sumit_yadav).pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
FAIRSpectra - Enabling the FAIRification of Spectroscopy and Spectrometry
FAIRSpectra - Enabling the FAIRification of Spectroscopy and SpectrometryFAIRSpectra - Enabling the FAIRification of Spectroscopy and Spectrometry
FAIRSpectra - Enabling the FAIRification of Spectroscopy and Spectrometry
 
Porella : features, morphology, anatomy, reproduction etc.
Porella : features, morphology, anatomy, reproduction etc.Porella : features, morphology, anatomy, reproduction etc.
Porella : features, morphology, anatomy, reproduction etc.
 
PATNA CALL GIRLS 8617370543 LOW PRICE ESCORT SERVICE
PATNA CALL GIRLS 8617370543 LOW PRICE ESCORT SERVICEPATNA CALL GIRLS 8617370543 LOW PRICE ESCORT SERVICE
PATNA CALL GIRLS 8617370543 LOW PRICE ESCORT SERVICE
 
CURRENT SCENARIO OF POULTRY PRODUCTION IN INDIA
CURRENT SCENARIO OF POULTRY PRODUCTION IN INDIACURRENT SCENARIO OF POULTRY PRODUCTION IN INDIA
CURRENT SCENARIO OF POULTRY PRODUCTION IN INDIA
 
FAIRSpectra - Enabling the FAIRification of Analytical Science
FAIRSpectra - Enabling the FAIRification of Analytical ScienceFAIRSpectra - Enabling the FAIRification of Analytical Science
FAIRSpectra - Enabling the FAIRification of Analytical Science
 
Human genetics..........................pptx
Human genetics..........................pptxHuman genetics..........................pptx
Human genetics..........................pptx
 
GBSN - Biochemistry (Unit 1)
GBSN - Biochemistry (Unit 1)GBSN - Biochemistry (Unit 1)
GBSN - Biochemistry (Unit 1)
 
Call Girls Ahmedabad +917728919243 call me Independent Escort Service
Call Girls Ahmedabad +917728919243 call me Independent Escort ServiceCall Girls Ahmedabad +917728919243 call me Independent Escort Service
Call Girls Ahmedabad +917728919243 call me Independent Escort Service
 
Molecular markers- RFLP, RAPD, AFLP, SNP etc.
Molecular markers- RFLP, RAPD, AFLP, SNP etc.Molecular markers- RFLP, RAPD, AFLP, SNP etc.
Molecular markers- RFLP, RAPD, AFLP, SNP etc.
 
GBSN - Microbiology (Unit 1)
GBSN - Microbiology (Unit 1)GBSN - Microbiology (Unit 1)
GBSN - Microbiology (Unit 1)
 
POGONATUM : morphology, anatomy, reproduction etc.
POGONATUM : morphology, anatomy, reproduction etc.POGONATUM : morphology, anatomy, reproduction etc.
POGONATUM : morphology, anatomy, reproduction etc.
 
Biogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune Waterworlds
Biogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune WaterworldsBiogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune Waterworlds
Biogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune Waterworlds
 

Scala Collections : Java 8 on Steroids

  • 1. Scala Collections : Java 8 on Steroids François Garillot Twitter : @huitseeker francois.garillot@typesafe.com 1
  • 3. What this talk is A look at Java 8 gives you 2-a
  • 4. What this talk is A look at Java 8 gives you ... and what it doesn’t 2-b
  • 5. What this talk is A look at Java 8 gives you ... and what it doesn’t A look at Scala collections 2-c
  • 6. What this talk is A look at Java 8 gives you ... and what it doesn’t A look at Scala collections A look at the why and how of collections 2-d
  • 7. What this talk is not 3
  • 8. What this talk is not New stuff 3-a
  • 9. What this talk is not New stuff Rocket Science 3-b
  • 10. What this talk is not New stuff Rocket Science Polemic 3-c
  • 12. What I’m hoping for A discussion 4-a
  • 13. What I’m hoping for A discussion Making things a tad more clear 4-b
  • 14. What I’m hoping for A discussion Making things a tad more clear ... or just less overlooked ? 4-c
  • 15. What I’m hoping for A discussion Making things a tad more clear ... or just less overlooked ? Not too boring 4-d
  • 16. What (functional, new things) you can do with Java 8 Lambda-expressions (String first, String second) -> Integer.compare(first.length(), second.length) Functional Interfaces Runnable r = () -> System.out.println("I am Runnable!"); Method references button.setOnAction(System.out::println); Constructor references List<String> labels = ... ; Stream<Button> buttonsStream = labels.stream().map(Button::new); Buttons[] buttonsArray = labels.stream().toArray(Button::new); int[]::new; 5
  • 17. The devil is in the details Optional<T>, Optional.of(), Optional.ofNullable(), Optional.empty() Default methods in interfaces. list.forEach(System.out::println) ... beware: SuperClasses win, Interfaces clash. ... And the standard library was not entirely rewritten (Path/Paths) Important topics : variable capture in closures, parallel execution. int[] counter = new int[1]; button.setOnAction(event -> counter[0]++); 6
  • 18. And also, Streams Any Collection has a stream() Stream.of() with a vararg, an array filter, map, flatMap, as well as plumbing: split, concat, limit Lazy processing, parallel() processing (you enforce statelessness) terminal reductions, e.g. reduce collector: HashSet<String> result = stream.collect(HashSet::new, HashSet::add, HashSet::addAll) Collector implementations (toList, toMap, ...) counting, maxBy, groupinBy, mapping, ... Beware: think about reuse. 7
  • 20. Interlude Does that make Java a functional programming language ? 8-a
  • 21. Interlude Does that make Java a functional programming language ? First class functions 8-b
  • 22. Interlude Does that make Java a functional programming language ? First class functions Technicalities 8-c
  • 23. Interlude Does that make Java a functional programming language ? First class functions Technicalities Does that make Java a Scala competitor ? 8-d
  • 24. Interlude Does that make Java a functional programming language ? First class functions Technicalities Does that make Java a Scala competitor ? Scala has never had a feature poverty problem. 8-e
  • 25. What you can’t do with Java 8 (yet) 1. Case classes 2. Pattern matching 3. Tail call elimination 4. Scoped access 5. Lazy keyword 6. Traits (well-scoped) 7. Rich Imports (local, aliased) 8. Macros 9. Backend (Miguel Garcia) 10. Specialization (Vlad Ureche) 11. Value classes 12. Implicits 13. Cake ! 9
  • 26. Collections The signatures of map Type classes & implicits Design goals 10
  • 28. The signatures of map def map[B](f: (A) ⇒ B) : Map[B] 11-a
  • 29. The signatures of map def map[B](f: (A) ⇒ B) : Map[B] But ... Type Constructor Polymorphism 11-b
  • 30. The signatures of map def map[B](f: (A) ⇒ B) : Map[B] But ... Type Constructor Polymorphism trait TraversableLike[+Elem, +Coll[+x]] { def map[NewElem](f: Elem ⇒ NewElem): Coll[NewElem] def filter(p: Elem ⇒ Boolean): Coll[Elem] } 11-c
  • 31. The signatures of map def map[B](f: (A) ⇒ B) : Map[B] But ... Type Constructor Polymorphism trait TraversableLike[+Elem, +Coll[+x]] { def map[NewElem](f: Elem ⇒ NewElem): Coll[NewElem] def filter(p: Elem ⇒ Boolean): Coll[Elem] } The idea that, whatever map needs, it will always deal with: 11-d
  • 32. The signatures of map def map[B](f: (A) ⇒ B) : Map[B] But ... Type Constructor Polymorphism trait TraversableLike[+Elem, +Coll[+x]] { def map[NewElem](f: Elem ⇒ NewElem): Coll[NewElem] def filter(p: Elem ⇒ Boolean): Coll[Elem] } The idea that, whatever map needs, it will always deal with: (Collection[Elements], Elements ⇒ OtherElements, Collection[OtherElements]) 11-e
  • 34. The signatures of map 12-a
  • 35. The signatures of map trait TraversableLike[+Elem, +Repr] { protected[this] def newBuilder: Builder[Elem, Repr] // deferred def foreach[U](f: Elem ⇒ U) // deferred def filter(p: Elem ⇒ Boolean): Repr = { val b = newBuilder foreach { elem <- if (p(elem)) b += elem } b.result } } class Builder[-Elem, +To] { def +=(elem: Elem): this.type = . . . def result(): To = . . . def clear() = . . . def mapResult[NewTo](f: To ⇒ NewTo): Builder[Elem, NewTo] = . . . } 12-b
  • 36. The signatures of map trait TraversableLike[+Elem, +Repr] { protected[this] def newBuilder: Builder[Elem, Repr] // deferred def foreach[U](f: Elem ⇒ U) // deferred def filter(p: Elem ⇒ Boolean): Repr = { val b = newBuilder foreach { elem <- if (p(elem)) b += elem } b.result } } class Builder[-Elem, +To] { def +=(elem: Elem): this.type = . . . def result(): To = . . . def clear() = . . . def mapResult[NewTo](f: To ⇒ NewTo): Builder[Elem, NewTo] = . . . } Why do we care ? Extensibility. 12-c
  • 37. The signatures of map (cont’d) 13
  • 38. The signatures of map (cont’d) 13-a
  • 39. The signatures of map (cont’d) def map[B, That](f: ((A,B)) ⇒ B) (implicit bf:CanBuildFrom[Map[A,B], B, That]):That 13-b
  • 40. The signatures of map (cont’d) def map[B, That](f: ((A,B)) ⇒ B) (implicit bf:CanBuildFrom[Map[A,B], B, That]):That Why ? 13-c
  • 41. The signatures of map (cont’d) def map[B, That](f: ((A,B)) ⇒ B) (implicit bf:CanBuildFrom[Map[A,B], B, That]):That Why ? Dealing with (Bitset, Int, BitSet) and (Bitset, String, Set[String]) 13-d
  • 42. The signatures of map (cont’d) def map[B, That](f: ((A,B)) ⇒ B) (implicit bf:CanBuildFrom[Map[A,B], B, That]):That Why ? Dealing with (Bitset, Int, BitSet) and (Bitset, String, Set[String]) Dealing with (Map[A, B], (A, B)) ⇒ (B, A), Map[B, A]) and (Map[A, B], (A, B)) ⇒ T, Iterable[T]) 13-e
  • 43. With Implicits trait CanBuildFrom[-Collection, -NewElem, +Result] { def apply(from: Collection): Builder[NewElem, Result] } trait TraversableLike[+A, +Repr] { def repr: Repr = . . . def foreach[U](f: A ⇒ U): Unit = . . . def map[B, To](f: A ⇒ B)(implicit cbf: CanBuildFrom[Repr, B, To]): To = { val b = cbf(repr) // get the builder from the CanBuildFrom instance for (x <- this) b += f(x) // transform element and add b.result } } 14
  • 44. trait SetLike[+A, +Repr] extends TraversableLike[A, Repr] { } trait BitSetLike[+This <: BitSetLike[This] with Set[Int]] extends SetLike[Int, This] {} trait Traversable[+A] extends TraversableLike[A, Traversable[A]] trait Set[+A] extends Traversable[A] with SetLike[A, Set[A]] class BitSet extends Set[Int] with BitSetLike[BitSet] object Set { implicit def canBuildFromSet[B] = new CanBuildFrom[Set[_], B, Set[B]] { def apply(from: Set[_]) = . . . } } object BitSet { implicit val canBuildFromBitSet = new CanBuildFrom[BitSet, Int, BitSet] { def apply(from: BitSet) = . . . } } 15