SlideShare a Scribd company logo
Scala is Java8.next()
Twitter - @blueiur
La-scala - daewon
// Before Java 8
Collections.sort(strings, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.compareTo(s2);
}
});

// Java 8
Collections.sort(strings, (s1, s2) -> s1.compareTo(s2));

Same thing different syntax
Programmer
โ—

http://office.naver.com
์˜ค! ๋ฒŒ์จ ์ƒˆ๋ฒฝ
3์‹œ๋„ค, ์ปดํ“จ
ํ„ฐ ๋„๊ณ  ์ž์•ผ
๊ฒ ์–ด!

Programmer
โ—

http://daewon.github.io/
ํ•œ ์‹œ๊ฐ„ ํ›„ ...
Overview
โ—
โ—

Scala
Java8 features
โ—‹
โ—‹

lambda
โ–  benefit of lambda expressions
comparison to Scala
โ—
โ—
โ—

Scalable Language
Born in 2003
Object-Oriented Meets Functional
Martin odersky
โ—
โ—

Designed the Scala programming language
Generic Java, and built the current generation of javac, the
Java compiler
Features
โ—
โ—
โ—
โ—
โ—
โ—

SEAMLESS JAVA INTEROP
TYPE INFERENCE
CONCURRENCY & DISTRIBUTION
TRAITS
PATTERN MATCHING
HIGHER-ORDER FUNCTIONS
Scala is used in many worldclass companies
Rod johnson joins typesafe
โ—
โ—

Creator of Spring
Keynote at ScalaDays 2013
โ—‹ Scala in 2018
โ—
โ—
โ—

Lambda Expressions
Method References
Virtual Extension Methods
โ—
โ—
โ—

Lambda Expressions
Method References
Virtual Extension Methods
Project Lambda - JSR 335
2006 - Gosling: "We will never have closures in Java"
2008 - Reinhold: "We will never have closures in Java"

Project Lambda
2007 - 3 different proposals for closures in Java
2009 - Start of project Lambda (JSR 335)

Project Lambda
JDK 8: General Availability - 2014/04/18
โ—‹
โ—‹
โ—‹
โ—‹

2006
2007
2008
2009

-

Gosling: "We will never have closures in Java"
3 different proposals for closures in Java
Reinhold: "We will never have closures in Java"
Start of project Lambda (JSR 335)
Lambda?
โ—
โ—
โ—
โ—

lambda calculus
anonymous function
function literal
closure
Lambda?
โ—
โ—
โ—
โ—

lambda calculus
anonymous function
function literal
closure
Anonymous Function
Wikipedia
โ—

function defined, and possibly called, without being bound
to an identifier.
์ต๋ช… ํ•จ์ˆ˜
Wikipedia
โ—

ํŠน์ • ์‹๋ณ„์ž ์—†์ด ์ •์˜๋˜๊ฑฐ๋‚˜ ํ˜ธ์ถœ๋  ์ˆ˜ ์žˆ๋Š” ํ•จ์ˆ˜
์ต๋ช… ํ•จ์ˆ˜
Wikipedia
โ—

ํŠน์ • ์‹๋ณ„์ž ์—†์ด ์ •์˜๋˜๊ฑฐ๋‚˜ ํ˜ธ์ถœ๋  ์ˆ˜ ์žˆ๋Š” ํ•จ์ˆ˜
Languages that support anonymous functions
ActionScript
Ada
C
C#
C++
Clojure
Curl
D
Dart
Dylan
Erlang
Elixir
F#
Frink
Go

Gosu
Groovy
Haskell
Java
JavaScript
Lisp
Logtalk
Lua
Mathematica
Maple
Matlab
Maxima
OCaml
Octave
Object Pascal

Objective-C
Pascal
Perl
PHP
Python
R
Racket
Ruby
Scala
Scheme
Smalltalk
Standard ML
TypeScript
Tcl
Vala
Visual Basic .NET
Visual Prolog
Languages that no support anonymous functions
ActionScript
Ada
C
C#
C++
Clojure
Curl
D
Dart
Dylan
Erlang
Elixir
F#
Frink
Go

Gosu
Groovy
Haskell
Java
JavaScript
Lisp
Logtalk
Lua
Mathematica
Maple
Matlab
Maxima
OCaml
Octave
Object Pascal

Objective-C
Pascal
Perl
PHP
Python
R
Racket
Ruby
Scala
Scheme
Smalltalk
Standard ML
TypeScript
Tcl
Vala
Visual Basic .NET
Visual Prolog
Languages that no support anonymous functions
ActionScript
Ada (1977)
C (1969)
C#
C++
Clojure
Curl
D
Dart
Dylan
Erlang
Elixir
F#
Frink
Go

Gosu
Groovy
Haskell
Java
JavaScript
Lisp
Logtalk
Lua
Mathematica
Maple
Matlab
Maxima
OCaml
Octave
Object Pascal

Objective-C
Pascal (1969)
Perl
PHP
Python
R
Racket
Ruby
Scala
Scheme
Smalltalk
Standard ML
TypeScript
Tcl
Vala
Visual Basic .NET
Visual Prolog
Languages that no support anonymous functions
ActionScript
Ada
C
C#
C++
Clojure
Curl
D
Dart
Dylan
Erlang
Elixir
F#
Frink
Go

Gosu
Groovy
Haskell
Java (1995)
JavaScript
Lisp
Logtalk
Lua
Mathematica
Maple
Matlab
Maxima
OCaml
Octave
Object Pascal

Objective-C
Pascal
Perl
PHP
Python
R
Racket
Ruby
Scala
Scheme
Smalltalk
Standard ML
TypeScript
Tcl
Vala
Visual Basic .NET
Visual Prolog
Java8 support Lambda
โ—

General Availability - 2014/04/18
Lambda syntax
โ—

(parameters) -> { body }

โ—

(int x, int y) -> { return x + y; }

Lambda Syntax
Lambda syntax
โ—
โ—
โ—
โ—

(param) -> {return 100}
(param) -> {100}
(param) -> 100
param -> 100

Lambda Syntax
Lambda syntax
โ—
โ—
โ—
โ—

(param) -> {return 100}
(param) -> {100}
(param) -> 100
param -> 100

Lambda Syntax
Lambda syntax
โ—
โ—
โ—
โ—

(param) -> {return 100}
(param) -> {100}
(param) -> 100
param -> 100

Lambda Syntax
Lambda syntax
โ—
โ—
โ—
โ—

(param) -> {return 100}
(param) -> {100}
(param) -> 100
param -> 100

Lambda Syntax
Lambda syntax
โ—
โ—
โ—
โ—

(param) -> {return 100}
(param) -> {100}
(param) -> 100
param -> 100

Lambda Syntax
Lambda syntax
โ—
โ—
โ—
โ—
โ—
โ—

x -> x + 1
(x) -> x + 1
(int x) -> x + 1
(int x, int y) -> x + y
(x, y) -> { System.out.println(x + y) }
() -> { System.out.println("runnable!"); }

Lambda Syntax
Storing Lambda
โ—
โ—
โ—

int n = 10;
String name = โ€œdaewonโ€;
? adder = (int x, int y) -> x + y
Storing Lambda
โ—
โ—
โ—

int n = 10;
String name = โ€œdaewonโ€;
? adder = (int x, int y) -> x + y
@Functional Interface
โ—

Lambda Expression -> Anonymous Inner Class
Replace with Lambda
@FunctionalInterface
interface Adder {
int add(int a, int b);
}

????? func = (int a, int b) -> { return a + b };
Adder shortFunc = (a, b) -> a + b;

Functional Interface
@FunctionalInterface
interface Adder {
int add(int a, int b);
}

Adder func = (int a, int b) -> { return a + b };
Adder shortFunc = (a, b) -> a + b;

Functional Interface
@FunctionalInterface
interface Adder {
int add(int a, int b);
}

Adder func = (int a, int b) -> { return a + b };
Adder shortFunc = (a, b) -> a + b;

Type Inference
Predefined Functional Interfaces
BiConsumer<T,U>
BiFunction<T,U,R>
BinaryOperator<T>
BiPredicate<T,U>
BooleanSupplier
Consumer<T>
DoubleBinaryOperator
DoubleConsumer
DoubleFunction<R>
DoublePredicate
DoubleSupplier
DoubleToIntFunction
DoubleToLongFunction
DoubleUnaryOperator
Function<T,R>
IntBinaryOperator
IntConsumer
IntFunction<R>

IntPredicate
IntSupplier
IntToDoubleFunction
IntToLongFunction
IntUnaryOperator
LongBinaryOperator
LongConsumer
LongFunction<R>
LongPredicate
LongSupplier
LongToDoubleFunction
LongToIntFunction
LongUnaryOperator
ObjDoubleConsumer<T>
ObjIntConsumer<T>
ObjLongConsumer<T>
Predicate<T>
Supplier<T>
Lambda in Java
โ—
โ—

anonymous inner class
lambda expressions
// Spring
jdbcTemplate.queryForObject("select * from student where id = ?",
new Object[]{1212l},
new RowMapper() {
public Object mapRow(ResultSet rs, int n) throws SQLException {
return new Student(rs.getString("name"), rs.getInt("age"));
}
});

// Google Guava
Iterables.filter(persons, new Predicate<Person>() {
public boolean apply(Person p) {
return p.getAge() > 18;
}
});
Lambda in Java
// Spring
jdbcTemplate.queryForObject("select * from student where id = ?",
new Object[]{1212l},
new RowMapper() {
public Object mapRow(ResultSet rs, int n) throws SQLException {
return new Student(rs.getString("name"), rs.getInt("age"));
}
});

// Google Guava
Iterables.filter(persons, new Predicate<Person>() {
public boolean apply(Person p) {
return p.getAge() > 18;
}
});
Lambda in Java
// Before Java 8
Collections.sort(strings, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.compareTo(s2);
}
});

// Java 8
Collections.sort(strings, (s1, s2) -> s1.compareTo(s2));

Bulky syntax!
// Java 8
Collections.sort(strings, (s1, s2) -> s1.compareTo(s2));

Clear syntax!
// Before Java 8
Collections.sort(strings, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.compareTo(s2);
}
});

// Java 8
Collections.sort(strings, (s1, s2) -> s1.compareTo(s2));

Same thing different syntax
Functions are Data
โ—
โ—
โ—

function as parameter
function as return value
lazy eval
ํ•จ์ˆ˜๋Š” ๋ฐ์ดํ„ฐ
โ—
โ—
โ—

ํ•จ์ˆ˜๋ฅผ ๋‹ค๋ฅธ ํ•จ์ˆ˜์— ์ธ์ž๋กœ ์‚ฌ์šฉ
ํ•จ์ˆ˜๋ฅผ ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜ ๊ฐ’์œผ๋กœ ์‚ฌ์šฉ
์ง€์—ฐ ํ‰๊ฐ€
ํ•จ์ˆ˜๋Š” ๋ฐ์ดํ„ฐ
โ—
โ—
โ—

ํ•จ์ˆ˜๋ฅผ ๋‹ค๋ฅธ ํ•จ์ˆ˜์— ์ธ์ž๋กœ ์‚ฌ์šฉ
ํ•จ์ˆ˜๋ฅผ ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜๊ฐ’์œผ๋กœ ์‚ฌ์šฉ
์ง€์—ฐ ํ‰๊ฐ€
Functions as parameter - Loan Pattern
โ—

scala_for_java_programmer
public void withFile(String fileName) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filename));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (bufferedReader != null)
bufferedReader.close();
}
}
Print each line to STDOUT
public void withFile(String fileName) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filename));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
DB.store(line);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (bufferedReader != null)
bufferedReader.close();
}
}
Store each line to DB
public void withFile(String fileName) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filename));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
// insert code at here
}
} catch (IOException ex) {
ex.printStackTrace();
System.out.println(line);
} finally {
if (bufferedReader != null)
DB.store(line);
bufferedReader.close();
}
}
Duplicate and Variation
public void withFile(String fileName, Consumer<String> work) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filename));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
work.accept(line);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (bufferedReader != null)
bufferedReader.close();
}
}
Refactoring with Lambda
public void withFile(String fileName, Consumer<String> work) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filename));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
work.accept(line);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (bufferedReader != null)
bufferedReader.close();
}
}
Refactoring with Lambda
// print each line to stdout
withFile(filename, line -> System.out.println(line));

// store each line to db
withFile(filename, line -> storeToDb(line));

// print and store each line
withFile(filename, line -> {
System.out.println(line)
storeToDb(line);
});

Refactoring with Lambda
// print each line to stdout
withFile(filename, line -> System.out.println(line));

// store each line to db
withFile(filename, line -> storeToDb(line));

Refactoring with Lambda
// Scala
def withFile(filename: String)(work: String => Unit) {
Source.fromFile(filename).getLines.forEach work
}

Scala
// Scala
def withFile(filename: String)(work: String => Unit) {
Source.fromFile(filename).getLines.forEach work
}

Scala
// Java8 - print each line to stdout
withFile(filename, line -> System.out.println(line));
// Java8 - store each line to db
withFile(filename, line -> storeToDb(line));

// Scala - print each line to stdout
withFile(filename) {
line => println(line)
}
// Scala - store each line to db
withFile(filename) {
line => storeToDb(line)
}
Multiple parameter lists(curried function)
Lambda with Collections
โ—
โ—

Imperative - external iteration
Functional - internal iteration
// External Iterator
for (Iterator iter = var.iterator(); iter.hasNext(); ) {
Object obj = iter.next();
// Operate on obj
}

// Internal Iterator
var.each( new Functor() {
public void operate(Object arg) {
arg *= 2;
}
});
Internal iterator? External iterator?
// External Iterator
for (Iterator iter = var.iterator(); iter.hasNext(); ) {
Object obj = iter.next();
// Operate on obj
}

// Internal Iterator
var.each( new Functor() {
public void operate(Object arg) {
arg *= 2;
}
});
When you pass a function object to a method to run over a
collection, that is an internal iterator
// External Iterator
for (Iterator iter = var.iterator(); iter.hasNext(); ) {
Object obj = iter.next();
// Operate on obj
}

// Internal Iterator
var.each( new Functor() {
public void operate(Object arg) {
arg *= 2;
}
});

์ปฌ๋ ‰์…˜์„ ์ˆœํšŒํ•˜๋Š” ๋™์•ˆ ํŠน์ • ํ–‰๋™์„ ํ•˜๋Š” ํ•จ์ˆ˜ ๊ฐ์ฒด๋ฅผ ์ „๋‹ฌํ•˜๋Š” ๋ฐฉ์‹์„
๋‚ด๋ถ€ ๋ฐ˜๋ณต์ž๋ผ๊ณ  ํ•œ๋‹ค
// External Iterator
for (Iterator iter = var.iterator(); iter.hasNext(); ) {
Object obj = iter.next();
// Operate on obj
}

// Internal Iterator
var.each( new Functor() {
public void operate(Object arg) {
arg *= 2;
}
});

์ปฌ๋ ‰์…˜์„ ์ˆœํšŒํ•˜๋Š” ๋™์•ˆ ํŠน์ • ํ–‰๋™์„ ํ•˜๋Š” ํ•จ์ˆ˜ ๊ฐ์ฒด๋ฅผ ์ „๋‹ฌํ•˜๋Š” ๋ฐฉ์‹์„
๋‚ด๋ถ€ ๋ฐ˜๋ณต์ž๋ผ๊ณ  ํ•œ๋‹ค
// Java8:: print each line to stdout
withFile(filename, line -> System.out.println(line));
// Java8 - store each line to db
withFile(filename, line -> storeToDb(line));
// Scala - print each line to stdout
withFile(filename) {
line => println(line)
}
// Scala:: store each line to db
withFile(filename) {
line => storeToDb(line)
}
Internal iterator
// Java8:: print each line to stdout
withFile(filename, line -> System.out.println(line));
// Java8 - store each line to db
withFile(filename, line -> storeToDb(line));
// Scala - print each line to stdout
withFile(filename) {
line => println(line)
}
// Scala:: store each line to db
withFile(filename) {
line => storeToDb(line)
}
Iterator
No more loop with Scala
โ—
โ—

Project Lambda J
Google guava-libraries/
case class Person(firstName: String, lastName: String, age:Int, male: Boolean)
case class Sale(buyer: Person, seller: Person, car: Car, cost: Double)
case class Car(brand: String, model: String, year: Int, originalValue: Double)

LambdaJ Demo Data Model
object db {
// car
val sonata = Car("Hyundai", "Sonata", 1982, 30000000)
val santafe = Car("Hyundai", "Santafe", 1990, 50000000)
val k7 = Car("KIA", "K7", 2000, 50000000)
val k9 = Car("KIA", "K9", 2008, 70000000)
val orlando = Car("GM", "Orlando", 2011, 30000000)
val chevrolet = Car("GM", "Chevrolet", 2010, 50000000)
val alpheon = Car("GM", "Alpheon", 2012, 70000000)
def cars = List(sonata, santafe, k7, k9, orlando, chevrolet, alpheon);
// person
val daewon = Person("daewon", "jeong", 31, true)
val youngtek = Person("youngtek", "hong", 32, true)
val jiwong = Person("jiwong", "kang", 34, true)
val taehee = Person("taehee", "kim", 32, false)
def persons = List(youngtek, daewon, jiwong, taehee)
// sales: map person/car
def sales = List(Sale(daewon, taehee, sonata, 30000000),
Sale(daewon, youngtek, santafe, 50000000),
Sale(daewon, jiwong, santafe, 50000000),
Sale(jiwong, taehee, santafe, 50000000),
Sale(taehee, daewon, chevrolet, 50000000),
Sale(youngtek, daewon, chevrolet, 50000000),
Sale(youngtek, taehee, orlando, 30000000),
Sale(taehee, jiwong, chevrolet, 30000000))
}
// Iterative version
List<Sale> salesOfAHyundai = new ArrayList<Sale>();
for (Sale sale : sales) {
if (sale.getCar().getBrand().equals("Hyundai")) {
salesOfAHyundai.add(sale);
}
}
// Functional version
val salesOfHyundai = db.sales.filter(_.car.brand == "Hyundai")

ํ˜„๋Œ€์ฐจ๋ฅผ ํŒ๋งคํ•˜๋Š” ๋ชจ๋“  Sales๊ฐ์ฒด๋ฅผ ์„ ํƒ
// Iterative version
List<Sale> salesOfAHyundai = new ArrayList<Sale>();
for (Sale sale : sales) {
if (sale.getCar().getBrand().equals("Hyundai")) {
salesOfAHyundai.add(sale);
}
}
// Functional version
val salesOfHyundai = db.sales.filter(_.car.brand == "Hyundai")

sales ๋ชฉ๋ก์—์„œ car brand๊ฐ€ Hyundai์ธ ๊ฒƒ๋งŒ ํ•„ํ„ฐ๋ง
// Iterative version
List<Sale> salesOfAHyundai = new ArrayList<Sale>();
for (Sale sale : sales) {
if (sale.getCar().getBrand().equals("Hyundai")) {
salesOfAHyundai.add(sale);
}
}
// Functional version
val salesOfHyundai = db.sales.filter(_.car.brand == "Hyundai")

Select all sales of Hyundai
// Iterative version
List<Double> costs = new ArrayList<Double>();
for (Car car : cars) {
costs.add(car.getOriginalValue());
}
// Functional version
val costs = db.cars.map(_.originalValue)

์ž๋™์ฐจ์— Original ๊ฐ€๊ฒฉ ๋ชฉ๋ก์„ ์ž‘์„ฑ
// Iterative version
List<Double> costs = new ArrayList<Double>();
for (Car car : cars) {
costs.add(car.getOriginalValue());
}
// Functional version
val costs = db.cars.map(_.originalValue)

cars ๋ชฉ๋ก์œผ๋กœ๋ถ€ํ„ฐ originalValue๋ฅผ ์ถ”์ถœํ•ด์„œ ์ƒˆ ๋ชฉ๋ก์„ ์ž‘์„ฑ
// Iterative version
List<Double> costs = new ArrayList<Double>();
for (Car car : cars) {
costs.add(car.getOriginalValue());
}
// Functional version
val costs = db.cars.map(_.originalValue)

Extract carโ€™s original cost
// Iterative version
double maxCost = 0.0;
for (Sale sale : sales) {
double cost = sale.getCost();
if (cost > maxCost) {
maxCost = cost;
}
}
// Functional version
val maxCost = db.sales.maxBy(_.cost).cost

๊ฐ€์žฅ ๋น„์‹ธ๊ฒŒ ํŒ๋งคํ•œ ๊ฐ’์€?
// Iterative version
double maxCost = 0.0;
for (Sale sale : sales) {
double cost = sale.getCost();
if (cost > maxCost) {
maxCost = cost;
}
}
// Functional version
val maxCost = db.sales.maxBy(_.cost).cost

Find most costly sale
// Iterative version
// 01. find youngest person in persons
Person youngest = null;
for (Person person : persons){
if (youngest == null || person.getAge() < youngest.getAge()) {
youngest = person;
}
}
// 02. find buyer have age equal to younggest person
List<Sale> buys = new ArrayList<Sale>();
for (Sale sale : sales){
if (sale.getBuyer().equals(youngest)) {
buys.add(sale);
}
}
// Functional version
val youngestPerson = db.persons.minBy( _.age )
val buys = db.sales.filter( _.buyer == youngestPerson )

๊ฐ€์žฅ ์–ด๋ฆฐ ์‚ฌ๋žŒ๊ณผ ๋‚˜์ด๊ฐ€ ๊ฐ™์€ ํŒ๋งค์ž๋“ค ์ฐพ๊ธฐ
// Iterative version
// 01. find youngest person in persons
Person youngest = null;
for (Person person : persons){
if (youngest == null || person.getAge() < youngest.getAge()) {
youngest = person;
}
}
// 02. find buyer have age equal to younggest person
List<Sale> buys = new ArrayList<Sale>();
for (Sale sale : sales){
if (sale.getBuyer().equals(youngest)) {
buys.add(sale);
}
}
// Functional version
val youngestPerson = db.persons.minBy( _.age )
val buys = db.sales.filter( _.buyer == youngestPerson )

Find buys of youngest person
// 01. ๊ฐ€์žฅ ์–ด๋ฆฐ ์‚ฌ๋žŒ์„ ์ฐพ๊ณ 
val youngestPerson = db.persons.minBy( _.age )
// 02. ๊ฐ€์žฅ ์–ด๋ฆฐ ์‚ฌ๋žŒ๊ณผ ๋‚˜์ด๊ฐ€ ๊ฐ™์€ ํŒ๋งค์ž๋“ค์„ ์ฐพ๋Š”๋‹ค.
val buys = db.sales.filter( _.buyer == youngestPerson )

Find buys of youngest person
// Iterative version
Map<String, List<Car>> carsByBrand = new HashMap<>();
for (Car car : db.getCars()) {
List<Car> carList = carsByBrand.get(car);
if (carList == null){
carList = new ArrayList<Car>();
carsByBrand.put(car.getBrand(), carList);
}
carList.add(car);
}
// Functional version
val carsByBrand = db.cars.groupBy(_.brand)

brand ๊ธฐ์ค€์œผ๋กœ car๋ฅผ ๊ทธ๋ฃจํ•‘
// Iterative version
Map<String, List<Car>> carsByBrand = new HashMap<>();
for (Car car : db.getCars()) {
List<Car> carList = carsByBrand.get(car);
if (carList == null){
carList = new ArrayList<Car>();
carsByBrand.put(car.getBrand(), carList);
}
carList.add(car);
}
// Functional version
val carsByBrand = db.cars.groupBy(_.brand)

Select * from cars group by brand
// Iterative version
Map<String, List<Car>> carsByBrand = new HashMap<>();
for (Car car : db.getCars()) {
List<Car> carList = carsByBrand.get(car);
if (carList == null){
carList = new ArrayList<Car>();
carsByBrand.put(car.getBrand(), carList);
}
carList.add(car);
}
// Functional version
val carsByBrand = db.cars.groupBy(_.brand)

Index cars by brand
// Iterative version
Map<Car, Integer> carsBought = new HashMap<Car, Integer>();
for (Sale sale : sales) {
Car car = sale.getCar();
int boughtTimes = carsBought.get(car);
carsBought.put(car, boughtTimes == null ? 1 : boughtTimes+1);
}
Car mostBoughtCarIterative = null;
int boughtTimesIterative = 0;
for (Entry<Car, Integer> entry : carsBought.entrySet()) {
if (entry.getValue() > boughtTimesIterative) {
mostBoughtCarIterative = entry.getKey();
boughtTimesIterative = entry.getValue();
}
}

๊ฐ€์žฅ ๋งŽ์ด ๊ตฌ๋งคํ•œ ์ฐจ
// Functional version
val carsBought = db.sales.groupBy( _.car ).mapValues( _.length )
val mostBoughtCar = carsBought.maxBy {
case (_, boughtCount) => boughtCount
}._1
val boughtTimes = carsBought(mostBoughtCar)

Find most bought car
// Functional version
val carsBought = db.sales.groupBy( _.car ).mapValues( _.length )
val mostBoughtCar = carsBought.maxBy {
case (_, boughtCount) => boughtCount
}._1
val boughtTimes = carsBought(mostBoughtCar)

Find most bought car
// Iterative version
Map<Person,Map<Person,Sale>> map = new HashMap<Person, Map<Person,Sale>>();
for (Sale sale : sales) {
Person buyer = sale.getBuyer();
Map<Person, Sale> buyerMap = map.get(buyer);
if (buyerMap == null) {
buyerMap = new HashMap<Person, Sale>();
map.put(buyer, buyerMap);
}
buyerMap.put(sale.getSeller(), sale);
}
Person youngest = null;
Person oldest = null;
for (Person person : persons) {
if (youngest == null || person.getAge() < youngest.getAge()){
youngest = person;
}
if (oldest == null || person.getAge() > oldest.getAge()) {
oldest = person;
}
}
Group sales by
Sale saleFromYoungestToOldest = map.get(youngest).get(oldest);

buyer and sellers
// Functional version
val map = db.sales.groupBy(_.buyer).mapValues{
ls => ls.groupBy(_.seller).mapValues(_.head)
}
val youngest = db.persons.minBy(_.age)
val oldest = db.persons.maxBy(_.age)
val saleFromYoungestToOldest = map(youngest)(oldest)

Group sales by buyer and sellers
Java8 Streams vs Scala For Comprehension
โ—
โ—

streams and sql
โ—‹ how-java-emulates-sql
for comprehension
// sql
select sum(salary)
from people
where gender = 'FEMALE'
// Java8 stream with lambda
people.stream()
.filter(p -> p.getGender() == Person.Gender.FEMALE)
.mapToInt(p -> p.getSalary())
.sum();

๋ชจ๋“  ์—ฌ์„ฑ์˜ ๊ธ‰์—ฌ์˜ ํ•ฉ
// sql
select sum(salary)
from people
where gender = 'FEMALE'
// scala for comprehension
(for (p <- people;
(if p.gender == Person.Gender.FEMALE))
yield p.salary).sum()

Find the sum of all the salaries of all the females.
// sql
select sum(salary)
from people
where gender = 'FEMALE'
// scala for comprehension
(for (p <- people;
(if p.gender == Person.Gender.FEMALE))
yield p.salary).sum()

Find the sum of all the salaries of all the females.
// sql
select distinct(firstName)
from people
where gender = 'MALE'
// Java8 stream with lambda
people.stream()
.filter(p -> p.getGender() == Person.Gender.MALE)
.map(p -> p.getFirstName())
.distinct()

์ค‘๋ณต์„ ์ œ๊ฑฐํ•œ ๋ชจ๋“  ๋‚จ์„ฑ์˜ ์ด๋ฆ„
// sql
select distinct(firstName)
from people
where gender = 'MALE'
// scala for comprehension
(for (p <- people;
if (p.getGender == Person.Gender.MALE))
yield p.firstName).distinct

Prepare a list of all (distinct) first names of the males
// sql
select distinct(firstName)
from people
where gender = 'MALE'
// scala for comprehension
(for (p <- people;
if (p.getGender == Person.Gender.MALE))
yield p.firstName).distinct

Prepare a list of all (distinct) first names of the males
// sql
๋‚˜์ด๊ฐ€ ๊ฐ€์žฅ ๋งŽ์€ ๋‚จ์ž๋“ค
select *
from
people
where age =
(select max(age) from people where gender ='MALE' )
and
gender ='MALE'
// Java8
int maxAge = people.stream().max(
(p1, p2) -> p1.getAge() - p2.getAge()).get());
people.stream()
.filter(p -> p.getGender() == Person.Gender.MALE
&& p.getAge() == max_age)
.collect(Collections.toList()));
// scala for comprehension
for {
maxAge <- Seq(person.maxBy(_.age));
p <- people;
if (p.age == maxAge && p.gender == Person.Gender.MALE)
} yield p
Is Java8 a functional language?
โ—

What is Functional Programming?
โ—‹ Immutable state
โ—‹ Functions as first class citizens
โ—‹ Persistent data structure
Immutable
โ—
โ—

No setter
Variable must be final

final int i = 0;
while(i < 5) {
System.out.println("compile error!");
i++;
}
Persistent Data Structure
Java8
โ—
โ—
โ—

Immutable state
Functions as first class citizens
Persistent data structure

Scala
โ—
โ—
โ—

Immutable state
Functions as first class citizens
Persistent data structure
Java8 is not a functional language.
โ—
โ—
โ—

So what?

Real-world programming isn't always perfectly functional
Java is steel the most popular language in the world
Functional programming is not a silver bullet
์ž๋ฐ”๋Š” ํ•จ์ˆ˜ํ˜• ์–ธ์–ด๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค.
โ—
โ—
โ—

๊ทธ๋ž˜์„œ์š”?

Real-world ๋ฌธ์ œ๊ฐ€ ํ•ญ์ƒ ํ•จ์ˆ˜ํ˜•์— ์ ํ•ฉํ•˜์ง€๋Š” ์•Š์Šต๋‹ˆ๋‹ค
์ž๋ฐ”๋Š” ์—ฌ์ „ํžˆ ์„ธ๊ณ„์—์„œ ๊ฐ€์žฅ ๋งŽ์ด ์“ฐ์ด๊ณ  ์žˆ๋Š” ์–ธ์–ด์ž…๋‹ˆ๋‹ค
ํ•จ์ˆ˜ํ˜• ์–ธ์–ด๋Š” ์€ํƒ„ํ™˜์ด ์•„๋‹™๋‹ˆ๋‹ค
Java8 is Good!
Scala is Best!
One more thing
โ—

Lambda? Closure?
Lambda? Closure?
// lambda is just an anonymous function
Collection.filter(lists, e โ€‘> e.length() >= 5)

// closure is function that closes over the environment it was defined
int min = 5;
Collection.filter(lists, e -> e.length() >= min);
Lambda? Closure?
// lambda is just an anonymous function
Collection.filter(lists, e โ€‘> e.length() >= 5)

// closure is function that closes over the environment it was defined
int min = 5;
Collection.filter(lists, e -> e.length() >= min);
Lazy eval -

Better logging with Lambda
// log message only debug mode
public void debug(String message) {
if (log.isDebugEnabled()) {
log.log(message);
}
}

debug(some.expensive("operation"));

log expensive operation
// log message only debug mode
public void debug(String message) {
if (log.isDebugEnabled()) {
log.log(message);
}
}

debug(some.expensive("operation"));

log expensive operation
// log message only debug mode
public void debug(Consumer<String> consumer) {
if (log.isDebugEnabled()) {
log.log(consumer.accept());
}
}

debug(() -> some.expensive("operation"));

log expensive operation with Lambda
// log message only debug mode
public void debug(Consumer<String> consumer) {
if (log.isDebugEnabled()) {
log.log(consumer.accept());
}
}

debug(() -> some.expensive("operation"));

log expensive operation with Lambda
// without Lambda
debug(some.expensive("operation"));

// with Lambda
debug(() -> some.expensive("operation"));

bulk syntax!
// Scala
def debug(message: => String) {
if (log.isDebugEnabled) log.log(message)
}
debug(some.expensive("operation"))

Lazy eval in Scala
// Scala
def debug(message: => String) {
if (log.isDebugEnabled) log.log(message)
}
debug(some.expensive("operation"))

Lazy eval in Scala
// Java:: Eager eval
debug(some.expensive("operation"));
// Java8:: Lazy eval
debug(() -> some.expensive("operation"));
// scala:: Lazy eval
debug(some.expensive("operation"))
Question => Answer
// quiz
Lambda๋ฅผ ์ €์žฅ์‹œ ์‚ฌ์šฉ๋˜๋Š” ์ธํ„ฐํŽ˜์ด์Šค์— ์‚ฌ์šฉ๋˜๋Š” Annotation์€?

๊ฒฝํ’ˆ!

More Related Content

What's hot

Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
Logan Chien
ย 
Beyond Java: ์ž๋ฐ” 8์„ ์ค‘์‹ฌ์œผ๋กœ ๋ณธ ์ž๋ฐ”์˜ ํ˜์‹ 
Beyond Java: ์ž๋ฐ” 8์„ ์ค‘์‹ฌ์œผ๋กœ ๋ณธ ์ž๋ฐ”์˜ ํ˜์‹ Beyond Java: ์ž๋ฐ” 8์„ ์ค‘์‹ฌ์œผ๋กœ ๋ณธ ์ž๋ฐ”์˜ ํ˜์‹ 
Beyond Java: ์ž๋ฐ” 8์„ ์ค‘์‹ฌ์œผ๋กœ ๋ณธ ์ž๋ฐ”์˜ ํ˜์‹ 
Sungchul Park
ย 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
Mario Fusco
ย 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardMario Fusco
ย 
C++11
C++11C++11
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
ย 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and UtilitiesPramod Kumar
ย 
The Style of C++ 11
The Style of C++ 11The Style of C++ 11
The Style of C++ 11
Sasha Goldshtein
ย 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
ย 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
Ganesh Samarthyam
ย 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting Lambdas
Ganesh Samarthyam
ย 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
ย 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
David Gรณmez Garcรญa
ย 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
Mario Fusco
ย 
Monadic Java
Monadic JavaMonadic Java
Monadic JavaMario Fusco
ย 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshuSidd Singh
ย 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
pramode_ce
ย 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Chris Richardson
ย 
Idiomatic C++
Idiomatic C++Idiomatic C++
Idiomatic C++
Federico Ficarelli
ย 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
Sumant Tambe
ย 

What's hot (20)

Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
ย 
Beyond Java: ์ž๋ฐ” 8์„ ์ค‘์‹ฌ์œผ๋กœ ๋ณธ ์ž๋ฐ”์˜ ํ˜์‹ 
Beyond Java: ์ž๋ฐ” 8์„ ์ค‘์‹ฌ์œผ๋กœ ๋ณธ ์ž๋ฐ”์˜ ํ˜์‹ Beyond Java: ์ž๋ฐ” 8์„ ์ค‘์‹ฌ์œผ๋กœ ๋ณธ ์ž๋ฐ”์˜ ํ˜์‹ 
Beyond Java: ์ž๋ฐ” 8์„ ์ค‘์‹ฌ์œผ๋กœ ๋ณธ ์ž๋ฐ”์˜ ํ˜์‹ 
ย 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
ย 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
ย 
C++11
C++11C++11
C++11
ย 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
ย 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
ย 
The Style of C++ 11
The Style of C++ 11The Style of C++ 11
The Style of C++ 11
ย 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
ย 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
ย 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting Lambdas
ย 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
ย 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
ย 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
ย 
Monadic Java
Monadic JavaMonadic Java
Monadic Java
ย 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshu
ย 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
ย 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
ย 
Idiomatic C++
Idiomatic C++Idiomatic C++
Idiomatic C++
ย 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
ย 

Viewers also liked

Lambda expressions java8 - yousry
Lambda expressions java8 - yousryLambda expressions java8 - yousry
Lambda expressions java8 - yousry
yousry ibrahim
ย 
Java8 Lambda and Streams
Java8 Lambda and StreamsJava8 Lambda and Streams
Java8 Lambda and Streams
Mindfire Solutions
ย 
Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8
Isuru Samaraweera
ย 
Java8
Java8Java8
Java8
Sunil Kumar
ย 
Boost your craftsmanship with Java 8
Boost your craftsmanship with Java 8Boost your craftsmanship with Java 8
Boost your craftsmanship with Java 8
Joรฃo Nunes
ย 
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
Sergii Maliarov
ย 
Java8 Neue Sprachfeatures - Lambda/Streams/default Methods/FunctionalInterfaces
Java8 Neue Sprachfeatures - Lambda/Streams/default Methods/FunctionalInterfacesJava8 Neue Sprachfeatures - Lambda/Streams/default Methods/FunctionalInterfaces
Java8 Neue Sprachfeatures - Lambda/Streams/default Methods/FunctionalInterfaces
Dirk Detering
ย 
Why is Java relevant? New features of Java8
Why is Java relevant? New features of Java8 Why is Java relevant? New features of Java8
Why is Java relevant? New features of Java8
xshyamx
ย 
2014 java functional
2014 java functional2014 java functional
2014 java functionalDemian Neidetcher
ย 
Java8
Java8Java8
Java8
Jadson Santos
ย 
Introduction to functional programming with java 8
Introduction to functional programming with java 8Introduction to functional programming with java 8
Introduction to functional programming with java 8
JavaBrahman
ย 
Java8 and Functional Programming
Java8 and Functional ProgrammingJava8 and Functional Programming
Java8 and Functional Programming
Yiguang Hu
ย 
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
JDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation streamJDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation stream
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
Ruslan Shevchenko
ย 
Java8 features
Java8 featuresJava8 features
Java8 features
Elias Hasnat
ย 
Java8 training - Class 1
Java8 training  - Class 1Java8 training  - Class 1
Java8 training - Class 1
Marut Singh
ย 
Java8 training - class 2
Java8 training - class 2Java8 training - class 2
Java8 training - class 2
Marut Singh
ย 
Java8 training - class 3
Java8 training - class 3Java8 training - class 3
Java8 training - class 3
Marut Singh
ย 
Java8 - Under the hood
Java8 - Under the hoodJava8 - Under the hood
Java8 - Under the hood
Lakshmi Narasimhan
ย 
Java 8 Date-Time API
Java 8 Date-Time APIJava 8 Date-Time API
Java 8 Date-Time API
Anindya Bandopadhyay
ย 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
Martin Toshev
ย 

Viewers also liked (20)

Lambda expressions java8 - yousry
Lambda expressions java8 - yousryLambda expressions java8 - yousry
Lambda expressions java8 - yousry
ย 
Java8 Lambda and Streams
Java8 Lambda and StreamsJava8 Lambda and Streams
Java8 Lambda and Streams
ย 
Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8
ย 
Java8
Java8Java8
Java8
ย 
Boost your craftsmanship with Java 8
Boost your craftsmanship with Java 8Boost your craftsmanship with Java 8
Boost your craftsmanship with Java 8
ย 
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
ย 
Java8 Neue Sprachfeatures - Lambda/Streams/default Methods/FunctionalInterfaces
Java8 Neue Sprachfeatures - Lambda/Streams/default Methods/FunctionalInterfacesJava8 Neue Sprachfeatures - Lambda/Streams/default Methods/FunctionalInterfaces
Java8 Neue Sprachfeatures - Lambda/Streams/default Methods/FunctionalInterfaces
ย 
Why is Java relevant? New features of Java8
Why is Java relevant? New features of Java8 Why is Java relevant? New features of Java8
Why is Java relevant? New features of Java8
ย 
2014 java functional
2014 java functional2014 java functional
2014 java functional
ย 
Java8
Java8Java8
Java8
ย 
Introduction to functional programming with java 8
Introduction to functional programming with java 8Introduction to functional programming with java 8
Introduction to functional programming with java 8
ย 
Java8 and Functional Programming
Java8 and Functional ProgrammingJava8 and Functional Programming
Java8 and Functional Programming
ย 
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
JDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation streamJDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation stream
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
ย 
Java8 features
Java8 featuresJava8 features
Java8 features
ย 
Java8 training - Class 1
Java8 training  - Class 1Java8 training  - Class 1
Java8 training - Class 1
ย 
Java8 training - class 2
Java8 training - class 2Java8 training - class 2
Java8 training - class 2
ย 
Java8 training - class 3
Java8 training - class 3Java8 training - class 3
Java8 training - class 3
ย 
Java8 - Under the hood
Java8 - Under the hoodJava8 - Under the hood
Java8 - Under the hood
ย 
Java 8 Date-Time API
Java 8 Date-Time APIJava 8 Date-Time API
Java 8 Date-Time API
ย 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
ย 

Similar to Scala is java8.next()

Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
Ian Robertson
ย 
Java 8
Java 8Java 8
Java 8
vilniusjug
ย 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
Tomasz Kowalczewski
ย 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
Venkateswaran Kandasamy
ย 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
Codemotion
ย 
Meetup C++ A brief overview of c++17
Meetup C++  A brief overview of c++17Meetup C++  A brief overview of c++17
Meetup C++ A brief overview of c++17
Daniel Eriksson
ย 
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
Databricks
ย 
Functional programming
Functional programmingFunctional programming
Functional programmingChristian Hujer
ย 
Lambdas and Laughs
Lambdas and LaughsLambdas and Laughs
Lambdas and Laughs
Jim Bethancourt
ย 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
RichardWarburton
ย 
Java 7 & 8 New Features
Java 7 & 8 New FeaturesJava 7 & 8 New Features
Java 7 & 8 New Features
Leandro Coutinho
ย 
Python Programming Basics for begginners
Python Programming Basics for begginnersPython Programming Basics for begginners
Python Programming Basics for begginners
Abishek Purushothaman
ย 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
NexThoughts Technologies
ย 
C# programming
C# programming C# programming
C# programming
umesh patil
ย 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
india_mani
ย 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
ย 
Reactive Programming in the Browser feat. Scala.js and PureScript
Reactive Programming in the Browser feat. Scala.js and PureScriptReactive Programming in the Browser feat. Scala.js and PureScript
Reactive Programming in the Browser feat. Scala.js and PureScript
Luka Jacobowitz
ย 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
Van Huong
ย 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
Guillaume Laforge
ย 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
Ahmed mar3y
ย 

Similar to Scala is java8.next() (20)

Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
ย 
Java 8
Java 8Java 8
Java 8
ย 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
ย 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
ย 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
ย 
Meetup C++ A brief overview of c++17
Meetup C++  A brief overview of c++17Meetup C++  A brief overview of c++17
Meetup C++ A brief overview of c++17
ย 
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
ย 
Functional programming
Functional programmingFunctional programming
Functional programming
ย 
Lambdas and Laughs
Lambdas and LaughsLambdas and Laughs
Lambdas and Laughs
ย 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
ย 
Java 7 & 8 New Features
Java 7 & 8 New FeaturesJava 7 & 8 New Features
Java 7 & 8 New Features
ย 
Python Programming Basics for begginners
Python Programming Basics for begginnersPython Programming Basics for begginners
Python Programming Basics for begginners
ย 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
ย 
C# programming
C# programming C# programming
C# programming
ย 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
ย 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
ย 
Reactive Programming in the Browser feat. Scala.js and PureScript
Reactive Programming in the Browser feat. Scala.js and PureScriptReactive Programming in the Browser feat. Scala.js and PureScript
Reactive Programming in the Browser feat. Scala.js and PureScript
ย 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
ย 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
ย 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
ย 

Recently uploaded

FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
ย 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
ย 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
ย 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
ย 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
ย 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
ย 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilotโ„ข
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilotโ„ขLe nuove frontiere dell'AI nell'RPA con UiPath Autopilotโ„ข
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilotโ„ข
UiPathCommunity
ย 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
ย 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
ย 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
ย 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
ย 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
ย 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
ย 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
ย 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
ย 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
ย 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
ย 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
ย 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
ย 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
ย 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
ย 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
ย 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
ย 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
ย 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
ย 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
ย 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilotโ„ข
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilotโ„ขLe nuove frontiere dell'AI nell'RPA con UiPath Autopilotโ„ข
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilotโ„ข
ย 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
ย 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
ย 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
ย 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
ย 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
ย 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
ย 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
ย 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
ย 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
ย 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
ย 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
ย 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ย 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
ย 

Scala is java8.next()

  • 1. Scala is Java8.next() Twitter - @blueiur La-scala - daewon
  • 2. // Before Java 8 Collections.sort(strings, new Comparator<String>() { @Override public int compare(String s1, String s2) { return s1.compareTo(s2); } }); // Java 8 Collections.sort(strings, (s1, s2) -> s1.compareTo(s2)); Same thing different syntax
  • 4. ์˜ค! ๋ฒŒ์จ ์ƒˆ๋ฒฝ 3์‹œ๋„ค, ์ปดํ“จ ํ„ฐ ๋„๊ณ  ์ž์•ผ ๊ฒ ์–ด! Programmer โ— http://daewon.github.io/ ํ•œ ์‹œ๊ฐ„ ํ›„ ...
  • 6. โ— โ— โ— Scalable Language Born in 2003 Object-Oriented Meets Functional
  • 7. Martin odersky โ— โ— Designed the Scala programming language Generic Java, and built the current generation of javac, the Java compiler
  • 8. Features โ— โ— โ— โ— โ— โ— SEAMLESS JAVA INTEROP TYPE INFERENCE CONCURRENCY & DISTRIBUTION TRAITS PATTERN MATCHING HIGHER-ORDER FUNCTIONS
  • 9. Scala is used in many worldclass companies
  • 10. Rod johnson joins typesafe โ— โ— Creator of Spring Keynote at ScalaDays 2013 โ—‹ Scala in 2018
  • 13. Project Lambda - JSR 335
  • 14. 2006 - Gosling: "We will never have closures in Java" 2008 - Reinhold: "We will never have closures in Java" Project Lambda
  • 15. 2007 - 3 different proposals for closures in Java 2009 - Start of project Lambda (JSR 335) Project Lambda
  • 16. JDK 8: General Availability - 2014/04/18 โ—‹ โ—‹ โ—‹ โ—‹ 2006 2007 2008 2009 - Gosling: "We will never have closures in Java" 3 different proposals for closures in Java Reinhold: "We will never have closures in Java" Start of project Lambda (JSR 335)
  • 19. Anonymous Function Wikipedia โ— function defined, and possibly called, without being bound to an identifier.
  • 20. ์ต๋ช… ํ•จ์ˆ˜ Wikipedia โ— ํŠน์ • ์‹๋ณ„์ž ์—†์ด ์ •์˜๋˜๊ฑฐ๋‚˜ ํ˜ธ์ถœ๋  ์ˆ˜ ์žˆ๋Š” ํ•จ์ˆ˜
  • 21. ์ต๋ช… ํ•จ์ˆ˜ Wikipedia โ— ํŠน์ • ์‹๋ณ„์ž ์—†์ด ์ •์˜๋˜๊ฑฐ๋‚˜ ํ˜ธ์ถœ๋  ์ˆ˜ ์žˆ๋Š” ํ•จ์ˆ˜
  • 22. Languages that support anonymous functions ActionScript Ada C C# C++ Clojure Curl D Dart Dylan Erlang Elixir F# Frink Go Gosu Groovy Haskell Java JavaScript Lisp Logtalk Lua Mathematica Maple Matlab Maxima OCaml Octave Object Pascal Objective-C Pascal Perl PHP Python R Racket Ruby Scala Scheme Smalltalk Standard ML TypeScript Tcl Vala Visual Basic .NET Visual Prolog
  • 23. Languages that no support anonymous functions ActionScript Ada C C# C++ Clojure Curl D Dart Dylan Erlang Elixir F# Frink Go Gosu Groovy Haskell Java JavaScript Lisp Logtalk Lua Mathematica Maple Matlab Maxima OCaml Octave Object Pascal Objective-C Pascal Perl PHP Python R Racket Ruby Scala Scheme Smalltalk Standard ML TypeScript Tcl Vala Visual Basic .NET Visual Prolog
  • 24. Languages that no support anonymous functions ActionScript Ada (1977) C (1969) C# C++ Clojure Curl D Dart Dylan Erlang Elixir F# Frink Go Gosu Groovy Haskell Java JavaScript Lisp Logtalk Lua Mathematica Maple Matlab Maxima OCaml Octave Object Pascal Objective-C Pascal (1969) Perl PHP Python R Racket Ruby Scala Scheme Smalltalk Standard ML TypeScript Tcl Vala Visual Basic .NET Visual Prolog
  • 25. Languages that no support anonymous functions ActionScript Ada C C# C++ Clojure Curl D Dart Dylan Erlang Elixir F# Frink Go Gosu Groovy Haskell Java (1995) JavaScript Lisp Logtalk Lua Mathematica Maple Matlab Maxima OCaml Octave Object Pascal Objective-C Pascal Perl PHP Python R Racket Ruby Scala Scheme Smalltalk Standard ML TypeScript Tcl Vala Visual Basic .NET Visual Prolog
  • 26. Java8 support Lambda โ— General Availability - 2014/04/18
  • 27. Lambda syntax โ— (parameters) -> { body } โ— (int x, int y) -> { return x + y; } Lambda Syntax
  • 28. Lambda syntax โ— โ— โ— โ— (param) -> {return 100} (param) -> {100} (param) -> 100 param -> 100 Lambda Syntax
  • 29. Lambda syntax โ— โ— โ— โ— (param) -> {return 100} (param) -> {100} (param) -> 100 param -> 100 Lambda Syntax
  • 30. Lambda syntax โ— โ— โ— โ— (param) -> {return 100} (param) -> {100} (param) -> 100 param -> 100 Lambda Syntax
  • 31. Lambda syntax โ— โ— โ— โ— (param) -> {return 100} (param) -> {100} (param) -> 100 param -> 100 Lambda Syntax
  • 32. Lambda syntax โ— โ— โ— โ— (param) -> {return 100} (param) -> {100} (param) -> 100 param -> 100 Lambda Syntax
  • 33. Lambda syntax โ— โ— โ— โ— โ— โ— x -> x + 1 (x) -> x + 1 (int x) -> x + 1 (int x, int y) -> x + y (x, y) -> { System.out.println(x + y) } () -> { System.out.println("runnable!"); } Lambda Syntax
  • 34. Storing Lambda โ— โ— โ— int n = 10; String name = โ€œdaewonโ€; ? adder = (int x, int y) -> x + y
  • 35. Storing Lambda โ— โ— โ— int n = 10; String name = โ€œdaewonโ€; ? adder = (int x, int y) -> x + y
  • 38. @FunctionalInterface interface Adder { int add(int a, int b); } ????? func = (int a, int b) -> { return a + b }; Adder shortFunc = (a, b) -> a + b; Functional Interface
  • 39. @FunctionalInterface interface Adder { int add(int a, int b); } Adder func = (int a, int b) -> { return a + b }; Adder shortFunc = (a, b) -> a + b; Functional Interface
  • 40. @FunctionalInterface interface Adder { int add(int a, int b); } Adder func = (int a, int b) -> { return a + b }; Adder shortFunc = (a, b) -> a + b; Type Inference
  • 42.
  • 43. Lambda in Java โ— โ— anonymous inner class lambda expressions
  • 44. // Spring jdbcTemplate.queryForObject("select * from student where id = ?", new Object[]{1212l}, new RowMapper() { public Object mapRow(ResultSet rs, int n) throws SQLException { return new Student(rs.getString("name"), rs.getInt("age")); } }); // Google Guava Iterables.filter(persons, new Predicate<Person>() { public boolean apply(Person p) { return p.getAge() > 18; } }); Lambda in Java
  • 45. // Spring jdbcTemplate.queryForObject("select * from student where id = ?", new Object[]{1212l}, new RowMapper() { public Object mapRow(ResultSet rs, int n) throws SQLException { return new Student(rs.getString("name"), rs.getInt("age")); } }); // Google Guava Iterables.filter(persons, new Predicate<Person>() { public boolean apply(Person p) { return p.getAge() > 18; } }); Lambda in Java
  • 46. // Before Java 8 Collections.sort(strings, new Comparator<String>() { @Override public int compare(String s1, String s2) { return s1.compareTo(s2); } }); // Java 8 Collections.sort(strings, (s1, s2) -> s1.compareTo(s2)); Bulky syntax!
  • 47. // Java 8 Collections.sort(strings, (s1, s2) -> s1.compareTo(s2)); Clear syntax!
  • 48. // Before Java 8 Collections.sort(strings, new Comparator<String>() { @Override public int compare(String s1, String s2) { return s1.compareTo(s2); } }); // Java 8 Collections.sort(strings, (s1, s2) -> s1.compareTo(s2)); Same thing different syntax
  • 49. Functions are Data โ— โ— โ— function as parameter function as return value lazy eval
  • 50. ํ•จ์ˆ˜๋Š” ๋ฐ์ดํ„ฐ โ— โ— โ— ํ•จ์ˆ˜๋ฅผ ๋‹ค๋ฅธ ํ•จ์ˆ˜์— ์ธ์ž๋กœ ์‚ฌ์šฉ ํ•จ์ˆ˜๋ฅผ ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜ ๊ฐ’์œผ๋กœ ์‚ฌ์šฉ ์ง€์—ฐ ํ‰๊ฐ€
  • 51. ํ•จ์ˆ˜๋Š” ๋ฐ์ดํ„ฐ โ— โ— โ— ํ•จ์ˆ˜๋ฅผ ๋‹ค๋ฅธ ํ•จ์ˆ˜์— ์ธ์ž๋กœ ์‚ฌ์šฉ ํ•จ์ˆ˜๋ฅผ ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜๊ฐ’์œผ๋กœ ์‚ฌ์šฉ ์ง€์—ฐ ํ‰๊ฐ€
  • 52. Functions as parameter - Loan Pattern โ— scala_for_java_programmer
  • 53. public void withFile(String fileName) { BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new FileReader(filename)); String line = null; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } } catch (IOException ex) { ex.printStackTrace(); } finally { if (bufferedReader != null) bufferedReader.close(); } } Print each line to STDOUT
  • 54. public void withFile(String fileName) { BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new FileReader(filename)); String line = null; while ((line = bufferedReader.readLine()) != null) { DB.store(line); } } catch (IOException ex) { ex.printStackTrace(); } finally { if (bufferedReader != null) bufferedReader.close(); } } Store each line to DB
  • 55. public void withFile(String fileName) { BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new FileReader(filename)); String line = null; while ((line = bufferedReader.readLine()) != null) { // insert code at here } } catch (IOException ex) { ex.printStackTrace(); System.out.println(line); } finally { if (bufferedReader != null) DB.store(line); bufferedReader.close(); } } Duplicate and Variation
  • 56. public void withFile(String fileName, Consumer<String> work) { BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new FileReader(filename)); String line = null; while ((line = bufferedReader.readLine()) != null) { work.accept(line); } } catch (IOException ex) { ex.printStackTrace(); } finally { if (bufferedReader != null) bufferedReader.close(); } } Refactoring with Lambda
  • 57. public void withFile(String fileName, Consumer<String> work) { BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new FileReader(filename)); String line = null; while ((line = bufferedReader.readLine()) != null) { work.accept(line); } } catch (IOException ex) { ex.printStackTrace(); } finally { if (bufferedReader != null) bufferedReader.close(); } } Refactoring with Lambda
  • 58. // print each line to stdout withFile(filename, line -> System.out.println(line)); // store each line to db withFile(filename, line -> storeToDb(line)); // print and store each line withFile(filename, line -> { System.out.println(line) storeToDb(line); }); Refactoring with Lambda
  • 59. // print each line to stdout withFile(filename, line -> System.out.println(line)); // store each line to db withFile(filename, line -> storeToDb(line)); Refactoring with Lambda
  • 60. // Scala def withFile(filename: String)(work: String => Unit) { Source.fromFile(filename).getLines.forEach work } Scala
  • 61. // Scala def withFile(filename: String)(work: String => Unit) { Source.fromFile(filename).getLines.forEach work } Scala
  • 62. // Java8 - print each line to stdout withFile(filename, line -> System.out.println(line)); // Java8 - store each line to db withFile(filename, line -> storeToDb(line)); // Scala - print each line to stdout withFile(filename) { line => println(line) } // Scala - store each line to db withFile(filename) { line => storeToDb(line) } Multiple parameter lists(curried function)
  • 63. Lambda with Collections โ— โ— Imperative - external iteration Functional - internal iteration
  • 64. // External Iterator for (Iterator iter = var.iterator(); iter.hasNext(); ) { Object obj = iter.next(); // Operate on obj } // Internal Iterator var.each( new Functor() { public void operate(Object arg) { arg *= 2; } }); Internal iterator? External iterator?
  • 65. // External Iterator for (Iterator iter = var.iterator(); iter.hasNext(); ) { Object obj = iter.next(); // Operate on obj } // Internal Iterator var.each( new Functor() { public void operate(Object arg) { arg *= 2; } }); When you pass a function object to a method to run over a collection, that is an internal iterator
  • 66. // External Iterator for (Iterator iter = var.iterator(); iter.hasNext(); ) { Object obj = iter.next(); // Operate on obj } // Internal Iterator var.each( new Functor() { public void operate(Object arg) { arg *= 2; } }); ์ปฌ๋ ‰์…˜์„ ์ˆœํšŒํ•˜๋Š” ๋™์•ˆ ํŠน์ • ํ–‰๋™์„ ํ•˜๋Š” ํ•จ์ˆ˜ ๊ฐ์ฒด๋ฅผ ์ „๋‹ฌํ•˜๋Š” ๋ฐฉ์‹์„ ๋‚ด๋ถ€ ๋ฐ˜๋ณต์ž๋ผ๊ณ  ํ•œ๋‹ค
  • 67. // External Iterator for (Iterator iter = var.iterator(); iter.hasNext(); ) { Object obj = iter.next(); // Operate on obj } // Internal Iterator var.each( new Functor() { public void operate(Object arg) { arg *= 2; } }); ์ปฌ๋ ‰์…˜์„ ์ˆœํšŒํ•˜๋Š” ๋™์•ˆ ํŠน์ • ํ–‰๋™์„ ํ•˜๋Š” ํ•จ์ˆ˜ ๊ฐ์ฒด๋ฅผ ์ „๋‹ฌํ•˜๋Š” ๋ฐฉ์‹์„ ๋‚ด๋ถ€ ๋ฐ˜๋ณต์ž๋ผ๊ณ  ํ•œ๋‹ค
  • 68. // Java8:: print each line to stdout withFile(filename, line -> System.out.println(line)); // Java8 - store each line to db withFile(filename, line -> storeToDb(line)); // Scala - print each line to stdout withFile(filename) { line => println(line) } // Scala:: store each line to db withFile(filename) { line => storeToDb(line) } Internal iterator
  • 69. // Java8:: print each line to stdout withFile(filename, line -> System.out.println(line)); // Java8 - store each line to db withFile(filename, line -> storeToDb(line)); // Scala - print each line to stdout withFile(filename) { line => println(line) } // Scala:: store each line to db withFile(filename) { line => storeToDb(line) } Iterator
  • 70. No more loop with Scala โ— โ— Project Lambda J Google guava-libraries/
  • 71. case class Person(firstName: String, lastName: String, age:Int, male: Boolean) case class Sale(buyer: Person, seller: Person, car: Car, cost: Double) case class Car(brand: String, model: String, year: Int, originalValue: Double) LambdaJ Demo Data Model
  • 72. object db { // car val sonata = Car("Hyundai", "Sonata", 1982, 30000000) val santafe = Car("Hyundai", "Santafe", 1990, 50000000) val k7 = Car("KIA", "K7", 2000, 50000000) val k9 = Car("KIA", "K9", 2008, 70000000) val orlando = Car("GM", "Orlando", 2011, 30000000) val chevrolet = Car("GM", "Chevrolet", 2010, 50000000) val alpheon = Car("GM", "Alpheon", 2012, 70000000) def cars = List(sonata, santafe, k7, k9, orlando, chevrolet, alpheon); // person val daewon = Person("daewon", "jeong", 31, true) val youngtek = Person("youngtek", "hong", 32, true) val jiwong = Person("jiwong", "kang", 34, true) val taehee = Person("taehee", "kim", 32, false) def persons = List(youngtek, daewon, jiwong, taehee) // sales: map person/car def sales = List(Sale(daewon, taehee, sonata, 30000000), Sale(daewon, youngtek, santafe, 50000000), Sale(daewon, jiwong, santafe, 50000000), Sale(jiwong, taehee, santafe, 50000000), Sale(taehee, daewon, chevrolet, 50000000), Sale(youngtek, daewon, chevrolet, 50000000), Sale(youngtek, taehee, orlando, 30000000), Sale(taehee, jiwong, chevrolet, 30000000)) }
  • 73. // Iterative version List<Sale> salesOfAHyundai = new ArrayList<Sale>(); for (Sale sale : sales) { if (sale.getCar().getBrand().equals("Hyundai")) { salesOfAHyundai.add(sale); } } // Functional version val salesOfHyundai = db.sales.filter(_.car.brand == "Hyundai") ํ˜„๋Œ€์ฐจ๋ฅผ ํŒ๋งคํ•˜๋Š” ๋ชจ๋“  Sales๊ฐ์ฒด๋ฅผ ์„ ํƒ
  • 74. // Iterative version List<Sale> salesOfAHyundai = new ArrayList<Sale>(); for (Sale sale : sales) { if (sale.getCar().getBrand().equals("Hyundai")) { salesOfAHyundai.add(sale); } } // Functional version val salesOfHyundai = db.sales.filter(_.car.brand == "Hyundai") sales ๋ชฉ๋ก์—์„œ car brand๊ฐ€ Hyundai์ธ ๊ฒƒ๋งŒ ํ•„ํ„ฐ๋ง
  • 75. // Iterative version List<Sale> salesOfAHyundai = new ArrayList<Sale>(); for (Sale sale : sales) { if (sale.getCar().getBrand().equals("Hyundai")) { salesOfAHyundai.add(sale); } } // Functional version val salesOfHyundai = db.sales.filter(_.car.brand == "Hyundai") Select all sales of Hyundai
  • 76. // Iterative version List<Double> costs = new ArrayList<Double>(); for (Car car : cars) { costs.add(car.getOriginalValue()); } // Functional version val costs = db.cars.map(_.originalValue) ์ž๋™์ฐจ์— Original ๊ฐ€๊ฒฉ ๋ชฉ๋ก์„ ์ž‘์„ฑ
  • 77. // Iterative version List<Double> costs = new ArrayList<Double>(); for (Car car : cars) { costs.add(car.getOriginalValue()); } // Functional version val costs = db.cars.map(_.originalValue) cars ๋ชฉ๋ก์œผ๋กœ๋ถ€ํ„ฐ originalValue๋ฅผ ์ถ”์ถœํ•ด์„œ ์ƒˆ ๋ชฉ๋ก์„ ์ž‘์„ฑ
  • 78. // Iterative version List<Double> costs = new ArrayList<Double>(); for (Car car : cars) { costs.add(car.getOriginalValue()); } // Functional version val costs = db.cars.map(_.originalValue) Extract carโ€™s original cost
  • 79. // Iterative version double maxCost = 0.0; for (Sale sale : sales) { double cost = sale.getCost(); if (cost > maxCost) { maxCost = cost; } } // Functional version val maxCost = db.sales.maxBy(_.cost).cost ๊ฐ€์žฅ ๋น„์‹ธ๊ฒŒ ํŒ๋งคํ•œ ๊ฐ’์€?
  • 80. // Iterative version double maxCost = 0.0; for (Sale sale : sales) { double cost = sale.getCost(); if (cost > maxCost) { maxCost = cost; } } // Functional version val maxCost = db.sales.maxBy(_.cost).cost Find most costly sale
  • 81. // Iterative version // 01. find youngest person in persons Person youngest = null; for (Person person : persons){ if (youngest == null || person.getAge() < youngest.getAge()) { youngest = person; } } // 02. find buyer have age equal to younggest person List<Sale> buys = new ArrayList<Sale>(); for (Sale sale : sales){ if (sale.getBuyer().equals(youngest)) { buys.add(sale); } } // Functional version val youngestPerson = db.persons.minBy( _.age ) val buys = db.sales.filter( _.buyer == youngestPerson ) ๊ฐ€์žฅ ์–ด๋ฆฐ ์‚ฌ๋žŒ๊ณผ ๋‚˜์ด๊ฐ€ ๊ฐ™์€ ํŒ๋งค์ž๋“ค ์ฐพ๊ธฐ
  • 82. // Iterative version // 01. find youngest person in persons Person youngest = null; for (Person person : persons){ if (youngest == null || person.getAge() < youngest.getAge()) { youngest = person; } } // 02. find buyer have age equal to younggest person List<Sale> buys = new ArrayList<Sale>(); for (Sale sale : sales){ if (sale.getBuyer().equals(youngest)) { buys.add(sale); } } // Functional version val youngestPerson = db.persons.minBy( _.age ) val buys = db.sales.filter( _.buyer == youngestPerson ) Find buys of youngest person
  • 83. // 01. ๊ฐ€์žฅ ์–ด๋ฆฐ ์‚ฌ๋žŒ์„ ์ฐพ๊ณ  val youngestPerson = db.persons.minBy( _.age ) // 02. ๊ฐ€์žฅ ์–ด๋ฆฐ ์‚ฌ๋žŒ๊ณผ ๋‚˜์ด๊ฐ€ ๊ฐ™์€ ํŒ๋งค์ž๋“ค์„ ์ฐพ๋Š”๋‹ค. val buys = db.sales.filter( _.buyer == youngestPerson ) Find buys of youngest person
  • 84. // Iterative version Map<String, List<Car>> carsByBrand = new HashMap<>(); for (Car car : db.getCars()) { List<Car> carList = carsByBrand.get(car); if (carList == null){ carList = new ArrayList<Car>(); carsByBrand.put(car.getBrand(), carList); } carList.add(car); } // Functional version val carsByBrand = db.cars.groupBy(_.brand) brand ๊ธฐ์ค€์œผ๋กœ car๋ฅผ ๊ทธ๋ฃจํ•‘
  • 85. // Iterative version Map<String, List<Car>> carsByBrand = new HashMap<>(); for (Car car : db.getCars()) { List<Car> carList = carsByBrand.get(car); if (carList == null){ carList = new ArrayList<Car>(); carsByBrand.put(car.getBrand(), carList); } carList.add(car); } // Functional version val carsByBrand = db.cars.groupBy(_.brand) Select * from cars group by brand
  • 86. // Iterative version Map<String, List<Car>> carsByBrand = new HashMap<>(); for (Car car : db.getCars()) { List<Car> carList = carsByBrand.get(car); if (carList == null){ carList = new ArrayList<Car>(); carsByBrand.put(car.getBrand(), carList); } carList.add(car); } // Functional version val carsByBrand = db.cars.groupBy(_.brand) Index cars by brand
  • 87. // Iterative version Map<Car, Integer> carsBought = new HashMap<Car, Integer>(); for (Sale sale : sales) { Car car = sale.getCar(); int boughtTimes = carsBought.get(car); carsBought.put(car, boughtTimes == null ? 1 : boughtTimes+1); } Car mostBoughtCarIterative = null; int boughtTimesIterative = 0; for (Entry<Car, Integer> entry : carsBought.entrySet()) { if (entry.getValue() > boughtTimesIterative) { mostBoughtCarIterative = entry.getKey(); boughtTimesIterative = entry.getValue(); } } ๊ฐ€์žฅ ๋งŽ์ด ๊ตฌ๋งคํ•œ ์ฐจ
  • 88. // Functional version val carsBought = db.sales.groupBy( _.car ).mapValues( _.length ) val mostBoughtCar = carsBought.maxBy { case (_, boughtCount) => boughtCount }._1 val boughtTimes = carsBought(mostBoughtCar) Find most bought car
  • 89. // Functional version val carsBought = db.sales.groupBy( _.car ).mapValues( _.length ) val mostBoughtCar = carsBought.maxBy { case (_, boughtCount) => boughtCount }._1 val boughtTimes = carsBought(mostBoughtCar) Find most bought car
  • 90. // Iterative version Map<Person,Map<Person,Sale>> map = new HashMap<Person, Map<Person,Sale>>(); for (Sale sale : sales) { Person buyer = sale.getBuyer(); Map<Person, Sale> buyerMap = map.get(buyer); if (buyerMap == null) { buyerMap = new HashMap<Person, Sale>(); map.put(buyer, buyerMap); } buyerMap.put(sale.getSeller(), sale); } Person youngest = null; Person oldest = null; for (Person person : persons) { if (youngest == null || person.getAge() < youngest.getAge()){ youngest = person; } if (oldest == null || person.getAge() > oldest.getAge()) { oldest = person; } } Group sales by Sale saleFromYoungestToOldest = map.get(youngest).get(oldest); buyer and sellers
  • 91. // Functional version val map = db.sales.groupBy(_.buyer).mapValues{ ls => ls.groupBy(_.seller).mapValues(_.head) } val youngest = db.persons.minBy(_.age) val oldest = db.persons.maxBy(_.age) val saleFromYoungestToOldest = map(youngest)(oldest) Group sales by buyer and sellers
  • 92. Java8 Streams vs Scala For Comprehension โ— โ— streams and sql โ—‹ how-java-emulates-sql for comprehension
  • 93.
  • 94. // sql select sum(salary) from people where gender = 'FEMALE' // Java8 stream with lambda people.stream() .filter(p -> p.getGender() == Person.Gender.FEMALE) .mapToInt(p -> p.getSalary()) .sum(); ๋ชจ๋“  ์—ฌ์„ฑ์˜ ๊ธ‰์—ฌ์˜ ํ•ฉ
  • 95. // sql select sum(salary) from people where gender = 'FEMALE' // scala for comprehension (for (p <- people; (if p.gender == Person.Gender.FEMALE)) yield p.salary).sum() Find the sum of all the salaries of all the females.
  • 96. // sql select sum(salary) from people where gender = 'FEMALE' // scala for comprehension (for (p <- people; (if p.gender == Person.Gender.FEMALE)) yield p.salary).sum() Find the sum of all the salaries of all the females.
  • 97. // sql select distinct(firstName) from people where gender = 'MALE' // Java8 stream with lambda people.stream() .filter(p -> p.getGender() == Person.Gender.MALE) .map(p -> p.getFirstName()) .distinct() ์ค‘๋ณต์„ ์ œ๊ฑฐํ•œ ๋ชจ๋“  ๋‚จ์„ฑ์˜ ์ด๋ฆ„
  • 98. // sql select distinct(firstName) from people where gender = 'MALE' // scala for comprehension (for (p <- people; if (p.getGender == Person.Gender.MALE)) yield p.firstName).distinct Prepare a list of all (distinct) first names of the males
  • 99. // sql select distinct(firstName) from people where gender = 'MALE' // scala for comprehension (for (p <- people; if (p.getGender == Person.Gender.MALE)) yield p.firstName).distinct Prepare a list of all (distinct) first names of the males
  • 100. // sql ๋‚˜์ด๊ฐ€ ๊ฐ€์žฅ ๋งŽ์€ ๋‚จ์ž๋“ค select * from people where age = (select max(age) from people where gender ='MALE' ) and gender ='MALE' // Java8 int maxAge = people.stream().max( (p1, p2) -> p1.getAge() - p2.getAge()).get()); people.stream() .filter(p -> p.getGender() == Person.Gender.MALE && p.getAge() == max_age) .collect(Collections.toList())); // scala for comprehension for { maxAge <- Seq(person.maxBy(_.age)); p <- people; if (p.age == maxAge && p.gender == Person.Gender.MALE) } yield p
  • 101.
  • 102. Is Java8 a functional language? โ— What is Functional Programming? โ—‹ Immutable state โ—‹ Functions as first class citizens โ—‹ Persistent data structure
  • 103. Immutable โ— โ— No setter Variable must be final final int i = 0; while(i < 5) { System.out.println("compile error!"); i++; }
  • 105. Java8 โ— โ— โ— Immutable state Functions as first class citizens Persistent data structure Scala โ— โ— โ— Immutable state Functions as first class citizens Persistent data structure
  • 106. Java8 is not a functional language. โ— โ— โ— So what? Real-world programming isn't always perfectly functional Java is steel the most popular language in the world Functional programming is not a silver bullet
  • 107. ์ž๋ฐ”๋Š” ํ•จ์ˆ˜ํ˜• ์–ธ์–ด๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค. โ— โ— โ— ๊ทธ๋ž˜์„œ์š”? Real-world ๋ฌธ์ œ๊ฐ€ ํ•ญ์ƒ ํ•จ์ˆ˜ํ˜•์— ์ ํ•ฉํ•˜์ง€๋Š” ์•Š์Šต๋‹ˆ๋‹ค ์ž๋ฐ”๋Š” ์—ฌ์ „ํžˆ ์„ธ๊ณ„์—์„œ ๊ฐ€์žฅ ๋งŽ์ด ์“ฐ์ด๊ณ  ์žˆ๋Š” ์–ธ์–ด์ž…๋‹ˆ๋‹ค ํ•จ์ˆ˜ํ˜• ์–ธ์–ด๋Š” ์€ํƒ„ํ™˜์ด ์•„๋‹™๋‹ˆ๋‹ค
  • 108. Java8 is Good! Scala is Best!
  • 110. Lambda? Closure? // lambda is just an anonymous function Collection.filter(lists, e โ€‘> e.length() >= 5) // closure is function that closes over the environment it was defined int min = 5; Collection.filter(lists, e -> e.length() >= min);
  • 111. Lambda? Closure? // lambda is just an anonymous function Collection.filter(lists, e โ€‘> e.length() >= 5) // closure is function that closes over the environment it was defined int min = 5; Collection.filter(lists, e -> e.length() >= min);
  • 112. Lazy eval - Better logging with Lambda
  • 113. // log message only debug mode public void debug(String message) { if (log.isDebugEnabled()) { log.log(message); } } debug(some.expensive("operation")); log expensive operation
  • 114. // log message only debug mode public void debug(String message) { if (log.isDebugEnabled()) { log.log(message); } } debug(some.expensive("operation")); log expensive operation
  • 115. // log message only debug mode public void debug(Consumer<String> consumer) { if (log.isDebugEnabled()) { log.log(consumer.accept()); } } debug(() -> some.expensive("operation")); log expensive operation with Lambda
  • 116. // log message only debug mode public void debug(Consumer<String> consumer) { if (log.isDebugEnabled()) { log.log(consumer.accept()); } } debug(() -> some.expensive("operation")); log expensive operation with Lambda
  • 117. // without Lambda debug(some.expensive("operation")); // with Lambda debug(() -> some.expensive("operation")); bulk syntax!
  • 118. // Scala def debug(message: => String) { if (log.isDebugEnabled) log.log(message) } debug(some.expensive("operation")) Lazy eval in Scala
  • 119. // Scala def debug(message: => String) { if (log.isDebugEnabled) log.log(message) } debug(some.expensive("operation")) Lazy eval in Scala
  • 120. // Java:: Eager eval debug(some.expensive("operation")); // Java8:: Lazy eval debug(() -> some.expensive("operation")); // scala:: Lazy eval debug(some.expensive("operation"))
  • 122. // quiz Lambda๋ฅผ ์ €์žฅ์‹œ ์‚ฌ์šฉ๋˜๋Š” ์ธํ„ฐํŽ˜์ด์Šค์— ์‚ฌ์šฉ๋˜๋Š” Annotation์€? ๊ฒฝํ’ˆ!