SlideShare une entreprise Scribd logo
1  sur  52
Is Java 8 a Scala killer?
Urs Peter
upeter@xebia.com
@urs_peter
http://bit.ly/xc_is
Born in 2003 – 10 years old
Sponsored by EPFL
(École Polytechnique Fédérale de Lausanne – Switzerland)
Some Facts about Scala
Also co-designed Generic Java,
and built the current generation of javac.
Creator: Martin Odersky
Some Facts about Scala
Scala is fully interoperable with Java
Some Facts about Scala
Scala is used in many worldclass companies &
applications
Some Facts about Scala
There is a company behind Scala
Some Facts about Scala
…that offers a supported Stack
Some Facts about Scala
Recently joined Typesafe:
Some Facts about Scala
Java
1.7Lightweight Syntax
Strong Typing
FunctionalObject Oriented
Some Facts about Scala
May 2013
Some Facts about Scala
Thoughtworks Technology Radar
Scala
Play Framework
• JSRs
– JSR 335 Lambda Expressions and Virtual Extension
Methods (in debate since 2008)
– JSR 308 Annotations on Java Types
– JSR 310 Date and Time API
• Schedule:
– 2013/02/21 M7
– 2013/07/05 M8 (Final Release Candidate)
– 2013/09/09 GA (General Availability)
– Spring 2014
Java 8
Java 8
• JSRs
– JSR 335 Lambda Expressions and Virtual Extension
Methods (in debate since 2008)
– JSR 308 Annotations on Java Types
– JSR 310 Date and Time API
• Schedule:
– 2013/02/21 M7
– 2013/07/05 M8 (Final Release Candidate)
– 2013/09/09 GA (General Availability)
– Spring 2014
Java
• JSRs
– JSR 335 Lambda Expressions and Virtual Extension
Methods (in debate since 2008)
– JSR 308 Annotations on Java Types
– JSR 310 Date and Time API
• Schedule:
– 2013/02/21 M7
– 2013/07/05 M8 (Final Release Candidate)
– 2013/09/09 GA (General Availability)
– Spring 2014
8
Java 8 Lambda’s versus
Scala Functions
What’s so fun about Functional Programming anyway?
List<Integer> numbers = Arrays.asList(1,2,3);
Filter even numbers
Filter odd numbers
DuplicationVariation
List<Integer> res = new ArrayList<>();
for (Integer i : numbers) {
if( i % 2 == 0 ) res.add(i);
}
return res;
List<Integer> res = new ArrayList<>();
for (Integer i : numbers) {
if( i % 2 != 0 ) res.add(i);
}
return res;
From Imperative to
Functional in Java
interface Predicate<T> {
public boolean op(T item);
}
The Function: Varying computation
The Loop: Generic Control Structure
public List<T> filter(List<T> items, Predicate<? super T> predicate) {
List<T> res = new ArrayList<>();
for(T item : items) {
if(predicate.op(item)){
res.add(item);
}
}
return res;
}
List<Integer> res = new ArrayList<>();
for (Integer i : numbers) {
if( i % 2 == 0 ) res.add(i);
}
return res;
From Imperative to
Functional in Java
Generic Control Structure
==
Higher Order Function
List<Integer> numbers = Arrays.asList(1, 2, 3);
Filter even numbers
Filter odd numbers
List<Integer> result = filter(numbers, new Predicate<Integer>() {
public boolean op(Integer item) {
return item % 2 == 0;
}
});
List<Integer> result = filter(numbers, new Predicate<Integer>() {
public boolean op(Integer item) {
return item % 2 != 0;
}
});
From Imperative to
Functional in Java
Take Spring:
Take Google Guava:
jdbcTemplate.queryForObject("select * from student where id = ?",
new Object[]{1212l},
new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Student(rs.getString("name"), rs.getInt("age"));
}
});
Iterables.filter(persons, new Predicate<Person>() {
public boolean apply(Person p) {
return p.getAge() > 18;
}
});
Can you see it?
Is the Functional Concept new in Java?
Before (< Java 8)
List<Integer> result = filter(numbers, new Predicate<Integer>() {
public boolean op(Integer i) {
return i % 2 == 0;
}
});
After (>= Java 8)
Lambda Expressions can be used for
‘Functional Interfaces’ (here Predicate)
that have a single method
(here: boolean op(T f)).
List<Integer> result = filter(numbers, (Integer i) -> i % 2 == 0 );
Functional Programming with Lambda’s
Lambda Expression
==
Syntactic sugar
List<Integer> result = filter(numbers, (Integer i) -> i % 2 == 0);
List<Integer> result = filter(numbers, i -> i % 2 == 0);
No need to define the
type since it can be
inferred by the compiler.
Lambda Features
at one Glance
Java 8
Complete Lambda Expression
Lambda Expression with Type Inference
Turn an existing static method
with the same signature as
the functional interface into a
closure, using ::
Method Reference
at one Glance
Java 8
Boolean::booleanValue
refers to the instance that
the filter is iterating through.
Static Method References
Instance Method References
List<Boolean> trueOrFalse = Arrays.asList(true, false);
List<Boolean> trueOnly = filter(trueOrFalse, Boolean::booleanValue );
public class NumUtils {
public static boolean isEven(Integer i) {
return i % 2 == 0;
}
}
List<Integer> result = filter(numbers, NumUtils::isEven );
(Integer i) -> NumUtils.isEven(i)
(Boolean b) -> b.booleanValue()
Complete Lambda Expression
Java 8
Scala
Java 8 Lambda Expressions
versus Scala Functions
val result = filter(numbers, (i:Int) => i % 2 == 0)
List<Integer> result = filter(numbers, (Integer i) -> i % 2 == 0);
List<Integer> result = filter(numbers, i -> i % 2 == 0);
Lambda with type inference
Java 8
Scala
Java 8 Lambda Expressions
versus Scala Functions
val result = filter(numbers, i => i % 2 == 0)
List<Integer> result = filter(numbers, NumUtils::isEven);
Static Method References
Java 8
val result = filter(numbers, NumUtils.isEven)
Scala Every method that is not
called with its arguments is
automatically turned into a
Function.
Methods == Functions
Java 8 Lambda Expressions
versus Scala Functions
List<Boolean> trueOnly = filter(trueOrFalse, Boolean::booleanValue);
Instance Method References
Java 8
Java 8 Lambda Expressions
versus Scala Functions
Scala
Scala uses the _ (underscore) to
refer to the current instance that
is iterated through
val trueOnly = filter(trueOrFalse, _.booleanValue )
So, what’s the difference?
trait Seq[T] {
def filter(f:T => Boolean):Seq[T]
...
Higher Order Functions reveal the difference:
interface Predicate<T> {
public boolean op(T t);
}
Java 8
Scala
interface Collection<T> {
public Collection<T> filter(Predicate<T> p);
...
Scala has a
function syntax.
Every Higher Order Function needs a
specific Functional Interface in Java 8.
The compiler transforms this syntax to a
generic Function object. Therefore, no
Functional Interface needs to be defined.
class Function1[I, R] {
def apply(i:I): R
}
Detailed Comparison
Java 8 Lambda Expressions
Syntax is limited to calling Higher
Order Functions
Functions are interfaces with one
method
Lambda’s are Syntactic Sugar for
Functional Interfaces
Scala Functions
Have a syntax for defining and
calling Higher Order Functions
Functions are objects with methods
Rich Function Features:
– Function Composition
– Currying
– Call-by-name arguments
– PartialFunctions
– Pattern matching
Functions are First Class Citizens
fully supporting the Functional
Programming Paradigm
Taking off with Functional
Programming
Iterations in Java are ‘external’ by
default…
What is going on here?
List<Student> students = ...;
List<Student> topGrades = new ArrayList<Student>();
List<String> result = new ArrayList<String>();
for(Student student : students){
if(student.getGrade() >= 9) {
topGrades.add(student);
}
}
}
Collections.sort(topGrades, new Comparator<Student>() {
public int compare(Student student1, Student student2) {
return student1.getGrade().compareTo(student2.getGrade());
}
});
for(Student student : topGrades){
result.add(student.getFirstName() + " " + student.getLastName());
}
Java
Advantages:
• Re-use of generic, higher level control structures
• Less error prone
• More expressive and readable
• Chainable
Internal Iteration: When
Lambda’s/Functions start to shine
Ah, now I get it:
List<Student> students = ...
List<String> topGrades =
students.filter(s -> s.getScore() >= 9)
.sortedBy(Student::getLastName)
.map(s -> s.getFirstName() + " " + s.getLastName())
.into(new ArrayList<>());
Java 8
Not yet
available
Internal Iteration: When
Lambda’s/Functions start to shine
val students = ...
val topGrades =
students.filter(_.score >= 9)
.sortBy(_.lastName)
.map(s => s.firstName + " " + s.lastName)
Java 8
Scala
No need to use the into()
method. This happens in
Scala ‘automagically’
List<Student> students = ...
List<String> topGrades =
students.filter(s -> s.getScore() >= 9)
.sortedBy(Student::getLastName)
.map(s -> s.getFirstName() + " " + s.getLastName())
.into(new ArrayList<>());
Not yet
available
Higher Order Functions
Parallelism
Automatic collection conversion
Fast immutable data structures
Other
Detailed Comparison:
Collections & Lambda’s/Functions
Scala
Collections
Automatic conversion
from Java to Scala
collections
Java 8
Collections
How is it possible to add Higher Order Functions
(e.g. filter map foreach etc.) to the java.util.Collection interface without
breaking backwards compatibility?
interface Collection<T> {
public Collection<T> filter(Predicate<T> p);
public <R> Collection<R> map(Mapper<T, R> m);
...
‘Old’ Java code (prior Java 8) running in
JRE 8 would have to implement all the
new methods that offer ‘internal
iteration’ with Lambda’s.
Back to Java 8:
How to make it fit?
Java 8
…with default implementations for interfaces
aka Virtual Extension Methods!
interface Collection<T> {
public default Collection<T> filter(Predicate<? super T> p) {
Collection<T> res = new ArrayList<>();
for(T item : this) {
if(p.test(item)) {
res.add(item);
}
}
return res;
}
...
Back to Java 8:
How to make it fit?
Java 8
A closer look at Java 8’
Virtual Extension Methods
• Primary motivator is API evolution
(Backwards compatibility for Lambda’s in
Collections)
• Useful mechanism by itself:
Enables Multiple Inheritance of behavior
• Inspired by Scala traits (among others)
Let’s model the domain for a ‘futuristic’ game
Gun
fireAt(s:Ship)
Shield
hit() //50%
Medic
repair(s:Ship)
Ship
health:Integer
hit()
Possible characteristics of a Ship:
s.health = 10
repaired += 1
health - 1s.hit()
health - 2
Do we need Multiple Inheritance?
Possible Ship implementations:
Base MechanicFighterCommander
The Limits of
Single inheritance
Implementation Challenge: Single inheritance won’t work
Gun Shield Medic
Base
Commander
Fighter
Mechanic
The Limits of
Single inheritance
Adding Behavior to a Ship (Scala)
class Ship(var health:Int = 0) {
def hit() = health -= 2
}
trait Gun {
def fireAt(s:Ship) = s.hit
}
A trait is an interface with
an implementation
(behavior and/or state)
val goodFighter = new Ship(10) with Gun
val evilFighter = new Ship(10) with Gun
goodFighter.fireAt(evilFighter)
println(evilFighter.health)
> 8
It can be ‘mixed-in’ with a
class using the keyword:
with
Scala
Multiple Inheritance of Behavior
Adding Behavior to a Ship (Java 8)
class Ship {
int health = 0;
//constructor, getters, setters, hit method
}
interface Gun {
default void fireAt(Ship s) { s.hit(); }
}
class Fighter extends Ship implements Gun {…}
Fighter goodFighter = new Fighter(10);
Fighter evilFighter = new Fighter(10);
goodFighter.fireAt(evilFighter);
println(evilFighter.getHealth());
> 8
Works with Virtual
Extension Methods
Java 8
Multiple Inheritance of Behavior
Change Behavior of Ship (Scala)
class Ship(var health:Int = 0) {
def hit() = health -= 2
}
trait Shield {
self:Ship =>
override def hit() = self.health -= 1
}
val commander = new Ship(10) with Gun with Shield
val evilFighter = new Ship(10) with Gun
evilFighter.fireAt(commander)
println(commander.health)
> 9
Trait’s can have a self-
type. The self-type tells
with which class this trait
can be ‘mixed’.
The self-type provides
access to the ‘mixed-in’
class
Traits can override
methods of the
‘mixed-in’ class
Scala
Multiple Inheritance of Behavior
Change Behavior of Ship (Java 8)
val commander = new Ship(10) with Gun with Shield
val evilFighter = new Ship(10) with Gun
evilFighter.fireAt(commander)
println(commander.health)
> 9
class Ship(var health:Int = 0) {
def hit() = health -= 2
}
trait Shield {
self:Ship =>
override def hit() = self.health -= 1
}
Does not work with Virtual
Extension Methods (VEM)
Why?
• VEM cannot override methods of
a class (they are overridden)
• VEM have no self-types
Java 8
Multiple Inheritance of Behavior
Adding State and Behavior to Ship (Scala)
trait Medic {
var repaired = 0
def repair(s:Ship) = {
s.health = 10
repaired += 1
}
}
val medic = new Ship(10) with Shield with Medic
val brokenShip = new Ship(1) with Gun
medic.repair(brokenShip)
println(brokenShip.health)
> 10
println(medic.repaired)
> 1
A trait can have state.
Scala
Multiple Inheritance of State
val medic = new Ship(10) with Shield with Medic
val brokenShip = new Ship(1) with Gun
medic.repair(brokenShip)
println(brokenShip.health)
> 10
println(medic.repaired)
> 1
Adding State and Behavior to Ship (Java 8)
trait Medic {
var repaired = 0
def repair(s:Ship) = {
s.health = 10
repaired += 1
}
}
Does not work with Virtual
Extension Methods (VEM)
Why?
• VEM cannot have state
Java 8
Multiple Inheritance of State
Have methods
Have fields
Access implementing
class in a typesafe way
Override methods
Stackable
(call to super is linearized)
Intent
Scala
Traits
Multiple inheritance
‘without the issues’
Java 8
Virtual Extension Methods
Grow the
language
Scala Traits vs
Java 8 Virtual Extension Methods
Is there no better way to
“Grow the language”?
• What we really want is ‘a mechanism’ that adds ‘new
methods’ to ‘existing classes’
• Virtual Extension Methods solve this problem on the
interface level:
– When we extend the interface with defaults, all classes inheriting
from this interface gain the functionality
– E.g. Arrays.asList(1,2,3).forEach(i -> println(i));
• Drawback: limited to interfaces
• But how about: I want to extend existing
classes by myself too!
"You win %2.2f%n".format(333333.3333);
new java.util.Date().toString("yyyy-MM-dd");
Welcome to Scala Implicits
…or the ‘pimp my library pattern’
Implicits in Practice
implicit class RichDate(val date:Date) extends AnyVal {
def toString(pat:String):String = new SimpleDateFormat(pat).format(date)
}
new java.util.Date().toString("yyyy-MM-dd")
Add a new method to an existing class (pimp my library):
Scala
//compiler turns this into:
RichDate.methods$.toString(new Date(), "yyyy-MM-dd")
Scala
Lambda’s for Collections:
Scala solved it before…
import collection.JavaConversions._
java.util.Arrays.asList(1,2,3).foreach(i => println(i))
java.util.Arrays.asList(1,2,3).filter(_ % 2 == 0)
Import JavaConversions and you are done:
Now we have all Higher
Order Functions like
foreach, filter, map etc.
available
The JavaConversions object
contains implicits that
convert a java.util.Collection
into a Scala’s counterpart.
Scala
If Java 8 had chosen for implicits…
• A proven mechanism was added to add new
methods to existing classes without being limited to
interfaces
• API designers AND API users would be able to add
new methods to existing classes
• Bridging of API’s – like Google Guava to Java
Collections – would be possible
• Last but not least: the implicit mechanism is not new
in Java: How about: Autoboxing, Lambda’s?
Lambda’s/Functions
Multiple Inheritance
Is Java 8 a Scala killer?
ScalaJava 8
Syntactic sugar for
Functional Interfaces
Functions as First
Class Citizens
Of Behaviour Of Behaviour and
State ‘without the
issues’
Extend existing classes - Implicits
• The features of JSR 335 (Lambda’s and Virtual Extension Methods)
are definitely an improvement;
• Choosing Implicits above Virtual Extension Methods for preserving
backwards compatibility would have made Java 8 more powerful;
• Java 8’ new language constructs are not as features rich and
complete as in Scala.
Q & A
def ask(question: Any) = question match {
case "?" => "Another layer of abstraction"
case "???" => "It depends"
case _ => 42
}
Evalutation
http://bit.ly/xc_is

Contenu connexe

Tendances

Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentationVan Huong
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Ganesh Samarthyam
 
java 8 new features
java 8 new features java 8 new features
java 8 new features Rohit Verma
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: NotesRoberto Casadei
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project LambdaRahman USTA
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scalaakuklev
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and ClosuresSandip Kumar
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsNewCircle Training
 

Tendances (20)

Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Scala
ScalaScala
Scala
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
Google06
Google06Google06
Google06
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
Introducing Akka
Introducing AkkaIntroducing Akka
Introducing Akka
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Scala test
Scala testScala test
Scala test
 
Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 

En vedette

Convegno “APP & GAME Il benessere dei giovani verso comunità media-educative”...
Convegno “APP & GAME Il benessere dei giovani verso comunità media-educative”...Convegno “APP & GAME Il benessere dei giovani verso comunità media-educative”...
Convegno “APP & GAME Il benessere dei giovani verso comunità media-educative”...Doc. Laura Prosdocimo
 
фабрика лидера
фабрика лидерафабрика лидера
фабрика лидераOlgaAvgustan
 
Noves tendències powerp.
Noves tendències powerp.Noves tendències powerp.
Noves tendències powerp.ainhoac15
 
Desur convegno25 sett_small version
Desur convegno25 sett_small versionDesur convegno25 sett_small version
Desur convegno25 sett_small versionUmberto Mezzacapo
 
ข้อสอบ O net 51 ภาษาอังกฤษ
ข้อสอบ O net 51 ภาษาอังกฤษข้อสอบ O net 51 ภาษาอังกฤษ
ข้อสอบ O net 51 ภาษาอังกฤษsupakeat
 
Test (pptx)
Test (pptx)Test (pptx)
Test (pptx)olcar2
 
Laboratorio di Comunicazione Sostenibile Corso di Alta Formazione UniBo 2012-13
Laboratorio di Comunicazione Sostenibile Corso di Alta Formazione UniBo 2012-13Laboratorio di Comunicazione Sostenibile Corso di Alta Formazione UniBo 2012-13
Laboratorio di Comunicazione Sostenibile Corso di Alta Formazione UniBo 2012-13Umberto Mezzacapo
 
Convegno “APP & GAME Il benessere dei giovani verso comunità media-educative”...
Convegno “APP & GAME Il benessere dei giovani verso comunità media-educative”...Convegno “APP & GAME Il benessere dei giovani verso comunità media-educative”...
Convegno “APP & GAME Il benessere dei giovani verso comunità media-educative”...Doc. Laura Prosdocimo
 
Not texting and driving
Not texting and drivingNot texting and driving
Not texting and drivingacarne14
 
Top 5 Smartphones above Rs.30,000
Top 5 Smartphones above Rs.30,000Top 5 Smartphones above Rs.30,000
Top 5 Smartphones above Rs.30,000Kamendra Singh
 
Il benessere come fattore e obiettivo educativo
Il benessere come fattore e obiettivo educativoIl benessere come fattore e obiettivo educativo
Il benessere come fattore e obiettivo educativoDoc. Laura Prosdocimo
 
Lab com sost_caf2013_esercitazioni
Lab com sost_caf2013_esercitazioniLab com sost_caf2013_esercitazioni
Lab com sost_caf2013_esercitazioniUmberto Mezzacapo
 

En vedette (18)

Convegno “APP & GAME Il benessere dei giovani verso comunità media-educative”...
Convegno “APP & GAME Il benessere dei giovani verso comunità media-educative”...Convegno “APP & GAME Il benessere dei giovani verso comunità media-educative”...
Convegno “APP & GAME Il benessere dei giovani verso comunità media-educative”...
 
Flyer1cara2
Flyer1cara2Flyer1cara2
Flyer1cara2
 
фабрика лидера
фабрика лидерафабрика лидера
фабрика лидера
 
Noves tendències powerp.
Noves tendències powerp.Noves tendències powerp.
Noves tendències powerp.
 
Desur convegno25 sett_small version
Desur convegno25 sett_small versionDesur convegno25 sett_small version
Desur convegno25 sett_small version
 
ข้อสอบ O net 51 ภาษาอังกฤษ
ข้อสอบ O net 51 ภาษาอังกฤษข้อสอบ O net 51 ภาษาอังกฤษ
ข้อสอบ O net 51 ภาษาอังกฤษ
 
Test (pptx)
Test (pptx)Test (pptx)
Test (pptx)
 
Flyer1cara3
Flyer1cara3Flyer1cara3
Flyer1cara3
 
Laboratorio di Comunicazione Sostenibile Corso di Alta Formazione UniBo 2012-13
Laboratorio di Comunicazione Sostenibile Corso di Alta Formazione UniBo 2012-13Laboratorio di Comunicazione Sostenibile Corso di Alta Formazione UniBo 2012-13
Laboratorio di Comunicazione Sostenibile Corso di Alta Formazione UniBo 2012-13
 
Guiadel egel info
Guiadel egel infoGuiadel egel info
Guiadel egel info
 
Intalacion
IntalacionIntalacion
Intalacion
 
Convegno “APP & GAME Il benessere dei giovani verso comunità media-educative”...
Convegno “APP & GAME Il benessere dei giovani verso comunità media-educative”...Convegno “APP & GAME Il benessere dei giovani verso comunità media-educative”...
Convegno “APP & GAME Il benessere dei giovani verso comunità media-educative”...
 
Flyer1cara4
Flyer1cara4Flyer1cara4
Flyer1cara4
 
Not texting and driving
Not texting and drivingNot texting and driving
Not texting and driving
 
Top 5 Smartphones above Rs.30,000
Top 5 Smartphones above Rs.30,000Top 5 Smartphones above Rs.30,000
Top 5 Smartphones above Rs.30,000
 
Il benessere come fattore e obiettivo educativo
Il benessere come fattore e obiettivo educativoIl benessere come fattore e obiettivo educativo
Il benessere come fattore e obiettivo educativo
 
Lab com sost_caf2013_esercitazioni
Lab com sost_caf2013_esercitazioniLab com sost_caf2013_esercitazioni
Lab com sost_caf2013_esercitazioni
 
Rt camp
Rt campRt camp
Rt camp
 

Similaire à Is Java 8 a Scala Killer? Comparing Lambda Expressions and Functions"TITLE"Java 8 vs Scala - A Comparison of Lambda Expressions and Functional Programming" TITLE"Functional Programming in Java 8 and Scala - A Look at Lambda Expressions and Higher Order Functions

Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hotSergii Maliarov
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrencykshanth2101
 
whats new in java 8
whats new in java 8 whats new in java 8
whats new in java 8 Dori Waldman
 
Introduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkIntroduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkAngelo Leto
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvmIsaias Barroso
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxBruceLee275640
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIJörn Guy Süß JGS
 
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Sungchul Park
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8Raffi Khatchadourian
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesRaffi Khatchadourian
 

Similaire à Is Java 8 a Scala Killer? Comparing Lambda Expressions and Functions"TITLE"Java 8 vs Scala - A Comparison of Lambda Expressions and Functional Programming" TITLE"Functional Programming in Java 8 and Scala - A Look at Lambda Expressions and Higher Order Functions (20)

Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrency
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
whats new in java 8
whats new in java 8 whats new in java 8
whats new in java 8
 
Introduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkIntroduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with spark
 
Java8
Java8Java8
Java8
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
 
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
 
Of Lambdas and LINQ
Of Lambdas and LINQOf Lambdas and LINQ
Of Lambdas and LINQ
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to Interfaces
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 

Dernier

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
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
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
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
 
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
 
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
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
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
 
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
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
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
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
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
 

Dernier (20)

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
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
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
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
 
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
 
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
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
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
 
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
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
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
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
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
 

Is Java 8 a Scala Killer? Comparing Lambda Expressions and Functions"TITLE"Java 8 vs Scala - A Comparison of Lambda Expressions and Functional Programming" TITLE"Functional Programming in Java 8 and Scala - A Look at Lambda Expressions and Higher Order Functions

  • 1. Is Java 8 a Scala killer? Urs Peter upeter@xebia.com @urs_peter http://bit.ly/xc_is
  • 2. Born in 2003 – 10 years old Sponsored by EPFL (École Polytechnique Fédérale de Lausanne – Switzerland) Some Facts about Scala
  • 3. Also co-designed Generic Java, and built the current generation of javac. Creator: Martin Odersky Some Facts about Scala
  • 4. Scala is fully interoperable with Java Some Facts about Scala
  • 5. Scala is used in many worldclass companies & applications Some Facts about Scala
  • 6. There is a company behind Scala Some Facts about Scala
  • 7. …that offers a supported Stack Some Facts about Scala
  • 8. Recently joined Typesafe: Some Facts about Scala
  • 10. May 2013 Some Facts about Scala Thoughtworks Technology Radar Scala Play Framework
  • 11. • JSRs – JSR 335 Lambda Expressions and Virtual Extension Methods (in debate since 2008) – JSR 308 Annotations on Java Types – JSR 310 Date and Time API • Schedule: – 2013/02/21 M7 – 2013/07/05 M8 (Final Release Candidate) – 2013/09/09 GA (General Availability) – Spring 2014 Java 8
  • 12. Java 8 • JSRs – JSR 335 Lambda Expressions and Virtual Extension Methods (in debate since 2008) – JSR 308 Annotations on Java Types – JSR 310 Date and Time API • Schedule: – 2013/02/21 M7 – 2013/07/05 M8 (Final Release Candidate) – 2013/09/09 GA (General Availability) – Spring 2014
  • 13. Java • JSRs – JSR 335 Lambda Expressions and Virtual Extension Methods (in debate since 2008) – JSR 308 Annotations on Java Types – JSR 310 Date and Time API • Schedule: – 2013/02/21 M7 – 2013/07/05 M8 (Final Release Candidate) – 2013/09/09 GA (General Availability) – Spring 2014 8
  • 14. Java 8 Lambda’s versus Scala Functions What’s so fun about Functional Programming anyway?
  • 15. List<Integer> numbers = Arrays.asList(1,2,3); Filter even numbers Filter odd numbers DuplicationVariation List<Integer> res = new ArrayList<>(); for (Integer i : numbers) { if( i % 2 == 0 ) res.add(i); } return res; List<Integer> res = new ArrayList<>(); for (Integer i : numbers) { if( i % 2 != 0 ) res.add(i); } return res; From Imperative to Functional in Java
  • 16. interface Predicate<T> { public boolean op(T item); } The Function: Varying computation The Loop: Generic Control Structure public List<T> filter(List<T> items, Predicate<? super T> predicate) { List<T> res = new ArrayList<>(); for(T item : items) { if(predicate.op(item)){ res.add(item); } } return res; } List<Integer> res = new ArrayList<>(); for (Integer i : numbers) { if( i % 2 == 0 ) res.add(i); } return res; From Imperative to Functional in Java Generic Control Structure == Higher Order Function
  • 17. List<Integer> numbers = Arrays.asList(1, 2, 3); Filter even numbers Filter odd numbers List<Integer> result = filter(numbers, new Predicate<Integer>() { public boolean op(Integer item) { return item % 2 == 0; } }); List<Integer> result = filter(numbers, new Predicate<Integer>() { public boolean op(Integer item) { return item % 2 != 0; } }); From Imperative to Functional in Java
  • 18. Take Spring: Take Google Guava: jdbcTemplate.queryForObject("select * from student where id = ?", new Object[]{1212l}, new RowMapper() { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { return new Student(rs.getString("name"), rs.getInt("age")); } }); Iterables.filter(persons, new Predicate<Person>() { public boolean apply(Person p) { return p.getAge() > 18; } }); Can you see it? Is the Functional Concept new in Java?
  • 19. Before (< Java 8) List<Integer> result = filter(numbers, new Predicate<Integer>() { public boolean op(Integer i) { return i % 2 == 0; } }); After (>= Java 8) Lambda Expressions can be used for ‘Functional Interfaces’ (here Predicate) that have a single method (here: boolean op(T f)). List<Integer> result = filter(numbers, (Integer i) -> i % 2 == 0 ); Functional Programming with Lambda’s Lambda Expression == Syntactic sugar
  • 20. List<Integer> result = filter(numbers, (Integer i) -> i % 2 == 0); List<Integer> result = filter(numbers, i -> i % 2 == 0); No need to define the type since it can be inferred by the compiler. Lambda Features at one Glance Java 8 Complete Lambda Expression Lambda Expression with Type Inference
  • 21. Turn an existing static method with the same signature as the functional interface into a closure, using :: Method Reference at one Glance Java 8 Boolean::booleanValue refers to the instance that the filter is iterating through. Static Method References Instance Method References List<Boolean> trueOrFalse = Arrays.asList(true, false); List<Boolean> trueOnly = filter(trueOrFalse, Boolean::booleanValue ); public class NumUtils { public static boolean isEven(Integer i) { return i % 2 == 0; } } List<Integer> result = filter(numbers, NumUtils::isEven ); (Integer i) -> NumUtils.isEven(i) (Boolean b) -> b.booleanValue()
  • 22. Complete Lambda Expression Java 8 Scala Java 8 Lambda Expressions versus Scala Functions val result = filter(numbers, (i:Int) => i % 2 == 0) List<Integer> result = filter(numbers, (Integer i) -> i % 2 == 0);
  • 23. List<Integer> result = filter(numbers, i -> i % 2 == 0); Lambda with type inference Java 8 Scala Java 8 Lambda Expressions versus Scala Functions val result = filter(numbers, i => i % 2 == 0)
  • 24. List<Integer> result = filter(numbers, NumUtils::isEven); Static Method References Java 8 val result = filter(numbers, NumUtils.isEven) Scala Every method that is not called with its arguments is automatically turned into a Function. Methods == Functions Java 8 Lambda Expressions versus Scala Functions
  • 25. List<Boolean> trueOnly = filter(trueOrFalse, Boolean::booleanValue); Instance Method References Java 8 Java 8 Lambda Expressions versus Scala Functions Scala Scala uses the _ (underscore) to refer to the current instance that is iterated through val trueOnly = filter(trueOrFalse, _.booleanValue )
  • 26. So, what’s the difference? trait Seq[T] { def filter(f:T => Boolean):Seq[T] ... Higher Order Functions reveal the difference: interface Predicate<T> { public boolean op(T t); } Java 8 Scala interface Collection<T> { public Collection<T> filter(Predicate<T> p); ... Scala has a function syntax. Every Higher Order Function needs a specific Functional Interface in Java 8. The compiler transforms this syntax to a generic Function object. Therefore, no Functional Interface needs to be defined. class Function1[I, R] { def apply(i:I): R }
  • 27. Detailed Comparison Java 8 Lambda Expressions Syntax is limited to calling Higher Order Functions Functions are interfaces with one method Lambda’s are Syntactic Sugar for Functional Interfaces Scala Functions Have a syntax for defining and calling Higher Order Functions Functions are objects with methods Rich Function Features: – Function Composition – Currying – Call-by-name arguments – PartialFunctions – Pattern matching Functions are First Class Citizens fully supporting the Functional Programming Paradigm
  • 28. Taking off with Functional Programming
  • 29. Iterations in Java are ‘external’ by default… What is going on here? List<Student> students = ...; List<Student> topGrades = new ArrayList<Student>(); List<String> result = new ArrayList<String>(); for(Student student : students){ if(student.getGrade() >= 9) { topGrades.add(student); } } } Collections.sort(topGrades, new Comparator<Student>() { public int compare(Student student1, Student student2) { return student1.getGrade().compareTo(student2.getGrade()); } }); for(Student student : topGrades){ result.add(student.getFirstName() + " " + student.getLastName()); } Java
  • 30. Advantages: • Re-use of generic, higher level control structures • Less error prone • More expressive and readable • Chainable Internal Iteration: When Lambda’s/Functions start to shine Ah, now I get it: List<Student> students = ... List<String> topGrades = students.filter(s -> s.getScore() >= 9) .sortedBy(Student::getLastName) .map(s -> s.getFirstName() + " " + s.getLastName()) .into(new ArrayList<>()); Java 8 Not yet available
  • 31. Internal Iteration: When Lambda’s/Functions start to shine val students = ... val topGrades = students.filter(_.score >= 9) .sortBy(_.lastName) .map(s => s.firstName + " " + s.lastName) Java 8 Scala No need to use the into() method. This happens in Scala ‘automagically’ List<Student> students = ... List<String> topGrades = students.filter(s -> s.getScore() >= 9) .sortedBy(Student::getLastName) .map(s -> s.getFirstName() + " " + s.getLastName()) .into(new ArrayList<>()); Not yet available
  • 32. Higher Order Functions Parallelism Automatic collection conversion Fast immutable data structures Other Detailed Comparison: Collections & Lambda’s/Functions Scala Collections Automatic conversion from Java to Scala collections Java 8 Collections
  • 33. How is it possible to add Higher Order Functions (e.g. filter map foreach etc.) to the java.util.Collection interface without breaking backwards compatibility? interface Collection<T> { public Collection<T> filter(Predicate<T> p); public <R> Collection<R> map(Mapper<T, R> m); ... ‘Old’ Java code (prior Java 8) running in JRE 8 would have to implement all the new methods that offer ‘internal iteration’ with Lambda’s. Back to Java 8: How to make it fit? Java 8
  • 34. …with default implementations for interfaces aka Virtual Extension Methods! interface Collection<T> { public default Collection<T> filter(Predicate<? super T> p) { Collection<T> res = new ArrayList<>(); for(T item : this) { if(p.test(item)) { res.add(item); } } return res; } ... Back to Java 8: How to make it fit? Java 8
  • 35. A closer look at Java 8’ Virtual Extension Methods • Primary motivator is API evolution (Backwards compatibility for Lambda’s in Collections) • Useful mechanism by itself: Enables Multiple Inheritance of behavior • Inspired by Scala traits (among others)
  • 36. Let’s model the domain for a ‘futuristic’ game Gun fireAt(s:Ship) Shield hit() //50% Medic repair(s:Ship) Ship health:Integer hit() Possible characteristics of a Ship: s.health = 10 repaired += 1 health - 1s.hit() health - 2 Do we need Multiple Inheritance?
  • 37. Possible Ship implementations: Base MechanicFighterCommander The Limits of Single inheritance
  • 38. Implementation Challenge: Single inheritance won’t work Gun Shield Medic Base Commander Fighter Mechanic The Limits of Single inheritance
  • 39. Adding Behavior to a Ship (Scala) class Ship(var health:Int = 0) { def hit() = health -= 2 } trait Gun { def fireAt(s:Ship) = s.hit } A trait is an interface with an implementation (behavior and/or state) val goodFighter = new Ship(10) with Gun val evilFighter = new Ship(10) with Gun goodFighter.fireAt(evilFighter) println(evilFighter.health) > 8 It can be ‘mixed-in’ with a class using the keyword: with Scala Multiple Inheritance of Behavior
  • 40. Adding Behavior to a Ship (Java 8) class Ship { int health = 0; //constructor, getters, setters, hit method } interface Gun { default void fireAt(Ship s) { s.hit(); } } class Fighter extends Ship implements Gun {…} Fighter goodFighter = new Fighter(10); Fighter evilFighter = new Fighter(10); goodFighter.fireAt(evilFighter); println(evilFighter.getHealth()); > 8 Works with Virtual Extension Methods Java 8 Multiple Inheritance of Behavior
  • 41. Change Behavior of Ship (Scala) class Ship(var health:Int = 0) { def hit() = health -= 2 } trait Shield { self:Ship => override def hit() = self.health -= 1 } val commander = new Ship(10) with Gun with Shield val evilFighter = new Ship(10) with Gun evilFighter.fireAt(commander) println(commander.health) > 9 Trait’s can have a self- type. The self-type tells with which class this trait can be ‘mixed’. The self-type provides access to the ‘mixed-in’ class Traits can override methods of the ‘mixed-in’ class Scala Multiple Inheritance of Behavior
  • 42. Change Behavior of Ship (Java 8) val commander = new Ship(10) with Gun with Shield val evilFighter = new Ship(10) with Gun evilFighter.fireAt(commander) println(commander.health) > 9 class Ship(var health:Int = 0) { def hit() = health -= 2 } trait Shield { self:Ship => override def hit() = self.health -= 1 } Does not work with Virtual Extension Methods (VEM) Why? • VEM cannot override methods of a class (they are overridden) • VEM have no self-types Java 8 Multiple Inheritance of Behavior
  • 43. Adding State and Behavior to Ship (Scala) trait Medic { var repaired = 0 def repair(s:Ship) = { s.health = 10 repaired += 1 } } val medic = new Ship(10) with Shield with Medic val brokenShip = new Ship(1) with Gun medic.repair(brokenShip) println(brokenShip.health) > 10 println(medic.repaired) > 1 A trait can have state. Scala Multiple Inheritance of State
  • 44. val medic = new Ship(10) with Shield with Medic val brokenShip = new Ship(1) with Gun medic.repair(brokenShip) println(brokenShip.health) > 10 println(medic.repaired) > 1 Adding State and Behavior to Ship (Java 8) trait Medic { var repaired = 0 def repair(s:Ship) = { s.health = 10 repaired += 1 } } Does not work with Virtual Extension Methods (VEM) Why? • VEM cannot have state Java 8 Multiple Inheritance of State
  • 45. Have methods Have fields Access implementing class in a typesafe way Override methods Stackable (call to super is linearized) Intent Scala Traits Multiple inheritance ‘without the issues’ Java 8 Virtual Extension Methods Grow the language Scala Traits vs Java 8 Virtual Extension Methods
  • 46. Is there no better way to “Grow the language”? • What we really want is ‘a mechanism’ that adds ‘new methods’ to ‘existing classes’ • Virtual Extension Methods solve this problem on the interface level: – When we extend the interface with defaults, all classes inheriting from this interface gain the functionality – E.g. Arrays.asList(1,2,3).forEach(i -> println(i)); • Drawback: limited to interfaces • But how about: I want to extend existing classes by myself too! "You win %2.2f%n".format(333333.3333); new java.util.Date().toString("yyyy-MM-dd");
  • 47. Welcome to Scala Implicits …or the ‘pimp my library pattern’
  • 48. Implicits in Practice implicit class RichDate(val date:Date) extends AnyVal { def toString(pat:String):String = new SimpleDateFormat(pat).format(date) } new java.util.Date().toString("yyyy-MM-dd") Add a new method to an existing class (pimp my library): Scala //compiler turns this into: RichDate.methods$.toString(new Date(), "yyyy-MM-dd") Scala
  • 49. Lambda’s for Collections: Scala solved it before… import collection.JavaConversions._ java.util.Arrays.asList(1,2,3).foreach(i => println(i)) java.util.Arrays.asList(1,2,3).filter(_ % 2 == 0) Import JavaConversions and you are done: Now we have all Higher Order Functions like foreach, filter, map etc. available The JavaConversions object contains implicits that convert a java.util.Collection into a Scala’s counterpart. Scala
  • 50. If Java 8 had chosen for implicits… • A proven mechanism was added to add new methods to existing classes without being limited to interfaces • API designers AND API users would be able to add new methods to existing classes • Bridging of API’s – like Google Guava to Java Collections – would be possible • Last but not least: the implicit mechanism is not new in Java: How about: Autoboxing, Lambda’s?
  • 51. Lambda’s/Functions Multiple Inheritance Is Java 8 a Scala killer? ScalaJava 8 Syntactic sugar for Functional Interfaces Functions as First Class Citizens Of Behaviour Of Behaviour and State ‘without the issues’ Extend existing classes - Implicits • The features of JSR 335 (Lambda’s and Virtual Extension Methods) are definitely an improvement; • Choosing Implicits above Virtual Extension Methods for preserving backwards compatibility would have made Java 8 more powerful; • Java 8’ new language constructs are not as features rich and complete as in Scala.
  • 52. Q & A def ask(question: Any) = question match { case "?" => "Another layer of abstraction" case "???" => "It depends" case _ => 42 } Evalutation http://bit.ly/xc_is

Notes de l'éditeur

  1. Today, we are trying to find an answer about the slightly exaggerated question whether ‘Java 8 can kill Scala’ In order to do that we will look at the most influential language features Java 8 will introduce and compare them to Scala.Today I am going to talk about the new language features of Java 8 in comparison to Scala.Because I believe that by comparing different language paradigm’s we not only can broaden our horizion but can also gain a lot of insipring.First I’d like to know more about you, the audience. - Who’s primary language is Java?- Who has ever written a line of Scala code?- Who considers him/herself to be familiar with functional programming?
  2. First let’s look at key characteristics of ScalaHybrid language: incorporates both paradigm to the full extentStrong typing: typechecker at compile team elimiates a great deal of errors and therefore makes large codebases managable
  3. Let’s take a little detour and First let’s figure out what benefits Functions offer us.
  4. To figure this out we look at an imperative example in Java and transform it into a functional representationWhenever duplication is involved there must be a better solutionExplain problems
  5. Abstract the expression in the if statementCreate a controlstructure that works with this abstractionPredicate is used to customize the generic control structureI’ll use this term throughout my presentation that’s why I would like to clarify its meaning
  6. Reuse of control structureProblem with this approach is that the anonymous inner class sytnax is very verbose.
  7. All of these implementation use an internal iteration, calling the single method of the functional interface to customize the behaviourThe Functional Concept exists in Java but there was no language support for it.
  8. Until now, Java did not have language support for this style of programming. This changes with Lambda’sSnippet above and below is semantically exactly identical.The Lambda represents the essence of the anonymous class above: the method signature of op and an implementation.Lambda Expression can be used everywhere where a functional interface is used:What is a functional interface?In that sense a Lambda expression is simply a piece of syntactic sugar.With Lambda’s Java has finally gained the key ingredient for functional programming
  9. Full blown expressionWhat is type inference: compiler trickUse colon colonMethod reference is a means to extract a method out of an existing class.Take an existing method and apply it’s implementation everywhere were we would use a functional interface.
  10. Full blown expressionWhat is type inference: compiler trickUse colon colonMethod reference is a means to extract a method out of an existing class.Take an existing method and apply it’s implementation everywhere were we would use a functional interface.
  11. Scala’s type inference goes much further than the one Java offers.Scala’s type inference is considerably more complete.
  12. When it comes to method references Scala does not need a special sytax for that.Methods and functions are closely related in Scala
  13. When it comes to method references Scala does not need a special sytax for that.Benefit: you get type inference for freeFor a beginner the _ syntax might be a bit confusing; however when you program more often it will become familiar very quickly
  14. The features Lambda’s offer are all available in Scalaas well. They even almost look identical.What are higher order functions?
  15. Scala: There is no need to choose a corresponding functional interface: Due to Scala’s Type Inference combined with Functions as ‘First Class Citizens’ approach this is not necessary:
  16. So let’s sum up the differences we have figured out so far. (between lambdas/method references and Scala functions)This is not very surprising because Scala was designed as a functional language from scratch whereas in Java functional capabilities are added to the language in a late stage.Scala’s Function allow you to fully leverage the functional programming paradigmScala’s Function support the full feature set needed to do hard-core functional programming.
  17. For creating some contrast let’s look at a normal piece of Java code whose structure must look very familiar to a Java developer
  18. When we look at this representation on the contrary we should be able to understand what’s going on by simple reading it, as if it was a text.This piece of code is considerably easier to understand than the previous sample. Why? Because we program here on a different abstraction level.We use higher level buildingblocks (higher order functions) that are customized by means of Lambda’s. Because we can chain these building blocks we can achieve the same result as in the previous slide with considerably less lines of codeThe main benefit Lambda’s and corresponding higher order functions offer are that we program on a different abstraction level. More readable, because we program on a different abstraction levelWe have re-usable buildingblocks we can chain together to compute the desired computation.Compute a list containing the names of top-grade students sorted by their grade.
  19. That’s not all: Let’s look at a limitation introduces by external iterations.
  20. There is no reason why this piece of code cannot be executed in parallel.
  21. Not only a pitty but at a certain point in time not acceptable anymore.
  22. Because now we have this different abstraction level, the underlying implementation can change.
  23. When you do hard-core functional programming you will embrace immutability.Functional programming supports immutable paradigmWorking with Scala collections is a great experience. Lambda expressions will make the gap smaller.
  24. After having looked at Lambda expressions let’s go one step further: How can we bring Lambda support to java.util.Collection interface without breaking backwards compatiblity?Java Design team had to come with a solution, to deal with this backwards compatiblity issue
  25. This was an important question for the Java 8 designer to answerOnly then Lambda expression really add benefit
  26. Java also knows multiple inheritance of types
  27. The characteristics have no common hierarchy but ortagonal
  28. Constrain which class to mix inThis constraint has advantages: it gives you access to the mixed in class
  29. Constrain which class to mix inThis constraint has advantages: it gives you access to the mixed in class
  30. Constrain which class to mix inThis constraint has advantages: it gives you access to the mixed in class
  31. Constrain which class to mix inThis constraint has advantages: it gives you access to the mixed in class
  32. Show in repl
  33. Stackable: prevent the classical diamond problem known from classical multiple inheritanceYou end up with a non-deterministic situation
  34. Let’s take a step backAre Virtual Extension Methods a good choice for the problem at hand?That means only the creator of the interface is able to add extensions.
  35. The implicit conversion mechanism works quite simple:whenever the compiler encounters a method that does not belong to a type it looks for an implicit conversion in scope.If the Scala compiler encounters a method or class it does not know it looks for an implicit conversion method or class
  36. Implicits are used in various areas of the Scala code, one usage area is bridge different API’s
  37. This is not a robust application of implicits, for illustrative purposes only
  38. If the Scala compiler encounters a method or class it does not know it looks for an implicit conversion method or class
  39. JSR335: makes the gap with modern jvm languages considerably smallerHowever, Java 8 cannot be expected to be as advanced as Scala, because:- Java is burdened with considerable backwards compatibility constraints- Java was not designed from scratch to be a functional or multiple inheritance languageSo is are the Java 8 featues a Scala killer? Definitely not. They are additions and therefore not as well integrated as in Scala where they are core class constructs. My personal conclusion is that Java 8 is good for Java and Scala. Why: Java more popular, gap van Java naarScala smaller