SlideShare una empresa de Scribd logo
1 de 78
Java 8 and Beyond,
a Scala Story
Ittai Zeidman, September 2016
http://searchengineland.com/figz/wp-content/seloads/2015/06/evolution-seo-marketer-ss-1920.jpg
Ittai Zeidman
• @ittaiz
• Backend Engineering Lead @
Wix
• Clean Code Fanatic
• Scala lover
• Proud spouse and father of 3
Ittai Zeidman
• @ittaiz
• Backend Engineering Lead @
Wix
• Clean Code Fanatic
• Scala lover
• Proud spouse and father of 3
Preface
Preface
• Java 8 was released
in 2014
Preface
• Java 8 was released
in 2014
• Which begs the
question…
• Is Scala still relevant?
Preface
• Java 8 was released
in 2014
• Which begs the
question…
• Is Scala still relevant?
– Yes.
Preface
• Java 8 was released
in 2014
• Which begs the
question…
• Is Scala still relevant?
– Yes.
Preface
• Java 8 was released
in 2014
• Which begs the
question…
• Is Scala still relevant?
– Yes.
– This talk is about
convincing you!
Quick Agenda
• A bit of history
– The Java-Scala gap
– How Java 8 reduces it
– Remaining gaps
• A deeper dive into:
– Traits
– Type Inference
– Pattern matching
– Implicits
The Java-Scala gap (pre Java
8)Scala’s big selling
points:
• Lambdas
• Collections library
• Traits
• Type inference
• DSLs
• Implicits
The Java-Scala gap
(currently)Scala’s big selling
points:
• Lambdas
• Collections library
• Traits
• Type inference
• DSLs
• Implicits
There’s So Much More…
There’s So Much More…
For-comprehensions
Flexible scoping
Built-in tuples
Higher-kinded types
Declaration-site
variance
Macros
Bottom types
Structural types
Type members
Path-dependent types
Implicit conversions
RIGHT.
WHY SHOULD YOU CARE?
#1: TRAITS
Ye Olde Logging
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ClassWithLogs {
private static Logger log =
LoggerFactory.getLogger(ClassWithLogs.class);
public String getNormalizedName(Person person) {
log.info("getNormalizedName called");
log.debug("Normalizing " + person.toString());
String normalizedName =
person.getName().toUpperCase().trim();
log.debug("Normalized name is: " + normalizedName);
return normalizedName;
}
}
Ye Olde Logging
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ClassWithLogs {
private static Logger log =
LoggerFactory.getLogger(ClassWithLogs.class);
public String getNormalizedName(Person person) {
log.info("getNormalizedName called");
log.debug("Normalizing " + person.toString());
String normalizedName =
person.getName().toUpperCase().trim();
log.debug("Normalized name is: " + normalizedName);
return normalizedName;
}
}
Boilerplate
Ye Olde Logging
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ClassWithLogs {
private static Logger log =
LoggerFactory.getLogger(ClassWithLogs.class);
public String getNormalizedName(Person person) {
log.info("getNormalizedName called");
log.debug("Normalizing " + person.toString());
String normalizedName =
person.getName().toUpperCase().trim();
log.debug("Normalized name is: " + normalizedName);
return normalizedName;
}
}
Eager
Evaluation
Boilerplate
Ye Olde Logging
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ClassWithLogs {
private static Logger log =
LoggerFactory.getLogger(ClassWithLogs.class);
public String getNormalizedName(Person person) {
log.info("getNormalizedName called");
log.debug("Normalizing " + person.toString());
String normalizedName =
person.getName().toUpperCase().trim();
log.debug("Normalized name is: " + normalizedName);
return normalizedName;
}
}
Eager
Evaluation
Boilerplate
Improvement?
public class LoggingSample implements Logging {
public String getNormalizedName(Person person) {
logInfo("getNormalizedName called");
logDebug("Normalizing " + person.toString());
String normalizedName =
person.getName().toUpperCase().trim();
logDebug("Normalized name is: " +
normalizedName);
return normalizedName;
}
}
Improvement?
public class LoggingSample implements Logging {
public String getNormalizedName(Person person) {
logInfo("getNormalizedName called");
logDebug("Normalizing " + person.toString());
String normalizedName =
person.getName().toUpperCase().trim();
logDebug("Normalized name is: " +
normalizedName);
return normalizedName;
}
}
Improvement?
public class LoggingSample implements Logging {
public String getNormalizedName(Person person) {
logInfo("getNormalizedName called");
logDebug("Normalizing " + person.toString());
String normalizedName =
person.getName().toUpperCase().trim();
logDebug("Normalized name is: " +
normalizedName);
return normalizedName;
}
}
Java Interface Limitations
Java Interface Limitations
• No fields allowed
Java Interface Limitations
• No fields allowed
– Need Logger instance
Java Interface Limitations
• No fields allowed
– Need Logger instance
– Workaround: getter
public interface Logging {
Logger logger();
default void logDebug(String msg)
{
if (logger().isDebugEnabled())
logger().debug(msg);
}
default void logInfo(String msg) {
if (logger().isInfoEnabled())
logger().info(msg);
}
}
Java Interface Limitations
• No fields allowed
– Need Logger instance
– Workaround: getter
– But... boilerplate :-(
public interface Logging {
Logger logger();
default void logDebug(String msg)
{
if (logger().isDebugEnabled())
logger().debug(msg);
}
default void logInfo(String msg) {
if (logger().isInfoEnabled())
logger().info(msg);
}
}
Java Interface Limitations
• No fields allowed
– Need Logger instance
– Workaround: getter
– But... boilerplate :-(
• Only public methods
– Logging APIs visible!
– … as is logger()
public interface Logging {
Logger logger();
default void logDebug(String msg)
{
if (logger().isDebugEnabled())
logger().debug(msg);
}
default void logInfo(String msg) {
if (logger().isInfoEnabled())
logger().info(msg);
}
}
And Lazy Evaluation?
And Lazy Evaluation?
• Can be implemented with a lambda:
import java.util.function.Supplier;
default void logDebug(Supplier<String> message) {
if (getLogger().isDebugEnabled())
getLogger().debug(message.get());
}
And Lazy Evaluation?
• Can be implemented with a lambda:
import java.util.function.Supplier;
default void logDebug(Supplier<String> message) {
if (getLogger().isDebugEnabled())
getLogger().debug(message.get());
}
• But there’s boilerplate at the call site:
logDebug(() -> "Normalizing " +
person.toString());
Scala Traits
trait Logging {
private val logger =
LoggerFactory.getLogger(getClass)
protected def logWarn(msg: => String) =
if (logger.isWarnEnabled)
logger.warn(msg)
protected def logDebug(msg: => String) =
if (logger.isDebugEnabled)
logger.debug(msg)
}
Scala Traits
• Allow fields
trait Logging {
private val logger =
LoggerFactory.getLogger(getClass)
protected def logWarn(msg: => String) =
if (logger.isWarnEnabled)
logger.warn(msg)
protected def logDebug(msg: => String) =
if (logger.isDebugEnabled)
logger.debug(msg)
}
Scala Traits
• Allow fields
• Participate in
lifecycle
trait Logging {
private val logger =
LoggerFactory.getLogger(getClass)
protected def logWarn(msg: => String) =
if (logger.isWarnEnabled)
logger.warn(msg)
protected def logDebug(msg: => String) =
if (logger.isDebugEnabled)
logger.debug(msg)
}
Scala Traits
• Allow fields
• Participate in
lifecycle
• Support
visibility
trait Logging {
private val logger =
LoggerFactory.getLogger(getClass)
protected def logWarn(msg: => String) =
if (logger.isWarnEnabled)
logger.warn(msg)
protected def logDebug(msg: => String) =
if (logger.isDebugEnabled)
logger.debug(msg)
}
Scala Traits
• Allow fields
• Participate in
lifecycle
• Support
visibility
• Multiple
inheritance!
trait Logging {
private val logger =
LoggerFactory.getLogger(getClass)
protected def logWarn(msg: => String) =
if (logger.isWarnEnabled)
logger.warn(msg)
protected def logDebug(msg: => String) =
if (logger.isDebugEnabled)
logger.debug(msg)
}
Scala Traits
• Allow fields
• Participate in
lifecycle
• Support
visibility
• Multiple
inheritance!
• By Name
eval
trait Logging {
private val logger =
LoggerFactory.getLogger(getClass)
protected def logWarn(msg: => String) =
if (logger.isWarnEnabled)
logger.warn(msg)
protected def logDebug(msg: => String) =
if (logger.isDebugEnabled)
logger.debug(msg)
}
#2: TYPE INFERENCE
*https://visualizingreading.wikispaces.com/file/view/Detective2.gif/214220534/358x190/Detective2.gif
Type Inference
Type Inference
• …the analysis of a program to infer the
types of some or all expressions, usually
at compile time…
Type Inference
• …the analysis of a program to infer the
types of some or all expressions, usually
at compile time…
• A balance between Compile Time Safety
and Verbosity
Java’s Type Inference
Java’s Type Inference
• Generics class ClassWithGenerics {
<T> void generic(T param) {
println(someParameter);
}
}
...
generic(“some param”)
generic(5)
Java’s Type Inference
• Generics
• Project Coin
class ClassWithGenerics {
<T> void generic(T param) {
println(someParameter);
}
}
...
generic(“some param”)
generic(5)
Map<String, Int> keyCounter =
new HashMap<>();
Scala’s Type Inference
Scala’s Type Inference
• Generics
Scala’s Type Inference
• Generics
• Local variables
Scala’s Type Inference
• Generics
• Local variables
• Method return values
LET’S DIVE INTO SOME CODE
#3: PATTERN MATCHING
Java’s Switch Statement
Java’s Switch Statement
• Switch statement is incredibly limited
– Only supports primitives (and strings)
– No arbitrary expressions (e.g. guards)
– No result values
Java’s Switch Statement
• Switch statement is incredibly limited
– Only supports primitives (and strings)
– No arbitrary expressions (e.g. guards)
– No result values
• Workarounds are ugly
– Nested control structures
– Encoding enums instead of using types
Pattern Matching
• Pattern matching in
Scala:
Pattern Matching
• Pattern matching in
Scala:
– Allows arbitrary types
Pattern Matching
• Pattern matching in
Scala:
– Allows arbitrary types
– Supports guards
Pattern Matching
• Pattern matching in
Scala:
– Allows arbitrary types
– Supports guards
– Checks for
exhaustiveness
Pattern Matching
• Pattern matching in
Scala:
– Allows arbitrary types
– Supports guards
– Checks for
exhaustiveness
– User-extensible
Pattern Matching
• Pattern matching in
Scala:
– Allows arbitrary types
– Supports guards
– Checks for
exhaustiveness
– User-extensible
– Ubiquitous
LET’S DIVE INTO SOME CODE
#4: IMPLICITS
Passing Class info (generics)
Passing Class info (generics)
• Java’s idiom is passing Class<T> clazz
around
Passing Class info (generics)
• Java’s idiom is passing Class<T> clazz
around
• Scala supports implicit parameters
– These are filled in by the compiler
– Well-defined rules for implicit search
Enhancing third party code
Enhancing third party code
• Java’s idiom is verbose wrapper methods
Enhancing third party code
• Java’s idiom is verbose wrapper methods
• Scala supports implicit methods
– Verified at compile time
LET’S DIVE INTO SOME CODE
Scala’s Relevance
Scala’s Relevance
• Post Java 8
Scala’s Relevance
• Post Java 8 ✔
Scala’s Relevance
• Post Java 8
• Towards Java 9
✔
Scala’s Relevance
• Post Java 8
• Towards Java 9
✔
✔
Scala’s Relevance
• Post Java 8
• Towards Java 9
• Java 10
✔
✔
Scala’s Relevance
• Post Java 8
• Towards Java 9
• Java 10
✔
✔
?
QUESTIONS?
?
?
?
?
?
?
?
?
?
?
WE’RE DONE
HERE!
Thank you for listening
@ittaiz
http://il.linkedin.com/in/ittaiz
Sample Code:
https://github.com/ittaiz/scala-and-java8

Más contenido relacionado

La actualidad más candente

Fixing the Java Serialization Mess
Fixing the Java Serialization Mess Fixing the Java Serialization Mess
Fixing the Java Serialization Mess
Salesforce Engineering
 
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Christian Schneider
 
Agile Developer Immersion Workshop, LASTconf Melbourne, Australia, 19th July ...
Agile Developer Immersion Workshop, LASTconf Melbourne, Australia, 19th July ...Agile Developer Immersion Workshop, LASTconf Melbourne, Australia, 19th July ...
Agile Developer Immersion Workshop, LASTconf Melbourne, Australia, 19th July ...
Victoria Schiffer
 

La actualidad más candente (20)

Fixing the Java Serialization Mess
Fixing the Java Serialization Mess Fixing the Java Serialization Mess
Fixing the Java Serialization Mess
 
Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)
Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)
Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)
 
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
 
JavaZone 2014 - goto java;
JavaZone 2014 - goto java;JavaZone 2014 - goto java;
JavaZone 2014 - goto java;
 
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
 
DBI-Assisted Android Application Reverse Engineering
DBI-Assisted Android Application Reverse EngineeringDBI-Assisted Android Application Reverse Engineering
DBI-Assisted Android Application Reverse Engineering
 
Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020
Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020
Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020
 
Javantura v2 - Making Java web-apps Groovy - Franjo Žilić
Javantura v2 - Making Java web-apps Groovy - Franjo ŽilićJavantura v2 - Making Java web-apps Groovy - Franjo Žilić
Javantura v2 - Making Java web-apps Groovy - Franjo Žilić
 
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
 
RelProxy, Easy Class Reload and Scripting with Java
RelProxy, Easy Class Reload and Scripting with JavaRelProxy, Easy Class Reload and Scripting with Java
RelProxy, Easy Class Reload and Scripting with Java
 
What to expect from Java 9
What to expect from Java 9What to expect from Java 9
What to expect from Java 9
 
Code lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf LinzCode lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf Linz
 
Groovy AST Transformations
Groovy AST TransformationsGroovy AST Transformations
Groovy AST Transformations
 
Agile Developer Immersion Workshop, LASTconf Melbourne, Australia, 19th July ...
Agile Developer Immersion Workshop, LASTconf Melbourne, Australia, 19th July ...Agile Developer Immersion Workshop, LASTconf Melbourne, Australia, 19th July ...
Agile Developer Immersion Workshop, LASTconf Melbourne, Australia, 19th July ...
 
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
 
Andrea Lattuada, Gabriele Petronella - Building startups on Scala
Andrea Lattuada, Gabriele Petronella - Building startups on ScalaAndrea Lattuada, Gabriele Petronella - Building startups on Scala
Andrea Lattuada, Gabriele Petronella - Building startups on Scala
 
Java Advanced Features
Java Advanced FeaturesJava Advanced Features
Java Advanced Features
 
Sonar rules in action with walkmod
Sonar rules in action with walkmodSonar rules in action with walkmod
Sonar rules in action with walkmod
 
Who go Types in my Systems Programing!
Who go Types in my Systems Programing!Who go Types in my Systems Programing!
Who go Types in my Systems Programing!
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassJava Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug Class
 

Destacado

Fotos conica solucio
Fotos conica solucioFotos conica solucio
Fotos conica solucio
slegna3
 
Inicial 3 b
Inicial 3 bInicial 3 b
Inicial 3 b
slegna3
 
History of figures
History of figuresHistory of figures
History of figures
Alayne Tetor
 
Someone You Know: Final Portrait Project, Glenn Hirsch, Instructor
Someone You Know: Final Portrait Project, Glenn Hirsch, InstructorSomeone You Know: Final Portrait Project, Glenn Hirsch, Instructor
Someone You Know: Final Portrait Project, Glenn Hirsch, Instructor
glennhirsch
 
Inicial 3 c
Inicial 3 cInicial 3 c
Inicial 3 c
slegna3
 
The figure in art history
The figure in art historyThe figure in art history
The figure in art history
evefiiez
 
Inicial 3A
Inicial 3AInicial 3A
Inicial 3A
slegna3
 
009 enllaços i tangencies
009 enllaços i tangencies009 enllaços i tangencies
009 enllaços i tangencies
slegna3
 
La imatge en moviment
La imatge en movimentLa imatge en moviment
La imatge en moviment
slegna3
 
Proportions of the Figure
Proportions of the FigureProportions of the Figure
Proportions of the Figure
profmedina
 

Destacado (20)

09 enllaços i tangencies
09 enllaços i tangencies09 enllaços i tangencies
09 enllaços i tangencies
 
Fotos conica solucio
Fotos conica solucioFotos conica solucio
Fotos conica solucio
 
040 enllac poligonal
040 enllac poligonal040 enllac poligonal
040 enllac poligonal
 
Inicial 3 b
Inicial 3 bInicial 3 b
Inicial 3 b
 
Examples of the Human Figure in Art
Examples of the Human Figure in ArtExamples of the Human Figure in Art
Examples of the Human Figure in Art
 
History of figures
History of figuresHistory of figures
History of figures
 
Someone You Know: Final Portrait Project, Glenn Hirsch, Instructor
Someone You Know: Final Portrait Project, Glenn Hirsch, InstructorSomeone You Know: Final Portrait Project, Glenn Hirsch, Instructor
Someone You Know: Final Portrait Project, Glenn Hirsch, Instructor
 
037 quadrcula enllaços
037 quadrcula enllaços037 quadrcula enllaços
037 quadrcula enllaços
 
038 apunts enllac
038 apunts enllac038 apunts enllac
038 apunts enllac
 
Inicial 3 c
Inicial 3 cInicial 3 c
Inicial 3 c
 
History of the figure
History of the figureHistory of the figure
History of the figure
 
Cubist self portrait
Cubist self portraitCubist self portrait
Cubist self portrait
 
010 dibuixen una serp 2
010 dibuixen una serp 2010 dibuixen una serp 2
010 dibuixen una serp 2
 
Figure Drawing Examples
Figure Drawing ExamplesFigure Drawing Examples
Figure Drawing Examples
 
The figure in art history
The figure in art historyThe figure in art history
The figure in art history
 
Proportions of the human form
Proportions of the human formProportions of the human form
Proportions of the human form
 
Inicial 3A
Inicial 3AInicial 3A
Inicial 3A
 
009 enllaços i tangencies
009 enllaços i tangencies009 enllaços i tangencies
009 enllaços i tangencies
 
La imatge en moviment
La imatge en movimentLa imatge en moviment
La imatge en moviment
 
Proportions of the Figure
Proportions of the FigureProportions of the Figure
Proportions of the Figure
 

Similar a Java 8 and beyond, a scala story

Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Nayden Gochev
 
Aspect oriented programming_with_spring
Aspect oriented programming_with_springAspect oriented programming_with_spring
Aspect oriented programming_with_spring
Guo Albert
 
Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012
Anton Arhipov
 
Appsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaolaAppsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaola
drewz lin
 
DIとトレイとによるAndroid開発の効率化
DIとトレイとによるAndroid開発の効率化DIとトレイとによるAndroid開発の効率化
DIとトレイとによるAndroid開発の効率化
Tomoharu ASAMI
 
Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011
Anton Arhipov
 

Similar a Java 8 and beyond, a scala story (20)

Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
 
Aspect oriented programming_with_spring
Aspect oriented programming_with_springAspect oriented programming_with_spring
Aspect oriented programming_with_spring
 
Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012
 
Appsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaolaAppsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaola
 
HashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin InfrastructureHashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin Infrastructure
 
Instrumentation of Software Systems
Instrumentation of Software SystemsInstrumentation of Software Systems
Instrumentation of Software Systems
 
React inter3
React inter3React inter3
React inter3
 
Eric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemEric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build system
 
Java 8 Lambda
Java 8 LambdaJava 8 Lambda
Java 8 Lambda
 
Shiksharth com java_topics
Shiksharth com java_topicsShiksharth com java_topics
Shiksharth com java_topics
 
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 For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
 
DIとトレイとによるAndroid開発の効率化
DIとトレイとによるAndroid開発の効率化DIとトレイとによるAndroid開発の効率化
DIとトレイとによるAndroid開発の効率化
 
Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011
 
De Java 8 ate Java 14
De Java 8 ate Java 14De Java 8 ate Java 14
De Java 8 ate Java 14
 
Angular2
Angular2Angular2
Angular2
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
 
1_JavIntro
1_JavIntro1_JavIntro
1_JavIntro
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

Java 8 and beyond, a scala story

  • 1. Java 8 and Beyond, a Scala Story Ittai Zeidman, September 2016 http://searchengineland.com/figz/wp-content/seloads/2015/06/evolution-seo-marketer-ss-1920.jpg
  • 2. Ittai Zeidman • @ittaiz • Backend Engineering Lead @ Wix • Clean Code Fanatic • Scala lover • Proud spouse and father of 3
  • 3. Ittai Zeidman • @ittaiz • Backend Engineering Lead @ Wix • Clean Code Fanatic • Scala lover • Proud spouse and father of 3
  • 5. Preface • Java 8 was released in 2014
  • 6. Preface • Java 8 was released in 2014 • Which begs the question… • Is Scala still relevant?
  • 7. Preface • Java 8 was released in 2014 • Which begs the question… • Is Scala still relevant? – Yes.
  • 8. Preface • Java 8 was released in 2014 • Which begs the question… • Is Scala still relevant? – Yes.
  • 9. Preface • Java 8 was released in 2014 • Which begs the question… • Is Scala still relevant? – Yes. – This talk is about convincing you!
  • 10. Quick Agenda • A bit of history – The Java-Scala gap – How Java 8 reduces it – Remaining gaps • A deeper dive into: – Traits – Type Inference – Pattern matching – Implicits
  • 11. The Java-Scala gap (pre Java 8)Scala’s big selling points: • Lambdas • Collections library • Traits • Type inference • DSLs • Implicits
  • 12. The Java-Scala gap (currently)Scala’s big selling points: • Lambdas • Collections library • Traits • Type inference • DSLs • Implicits
  • 13. There’s So Much More…
  • 14. There’s So Much More… For-comprehensions Flexible scoping Built-in tuples Higher-kinded types Declaration-site variance Macros Bottom types Structural types Type members Path-dependent types Implicit conversions
  • 17. Ye Olde Logging import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ClassWithLogs { private static Logger log = LoggerFactory.getLogger(ClassWithLogs.class); public String getNormalizedName(Person person) { log.info("getNormalizedName called"); log.debug("Normalizing " + person.toString()); String normalizedName = person.getName().toUpperCase().trim(); log.debug("Normalized name is: " + normalizedName); return normalizedName; } }
  • 18. Ye Olde Logging import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ClassWithLogs { private static Logger log = LoggerFactory.getLogger(ClassWithLogs.class); public String getNormalizedName(Person person) { log.info("getNormalizedName called"); log.debug("Normalizing " + person.toString()); String normalizedName = person.getName().toUpperCase().trim(); log.debug("Normalized name is: " + normalizedName); return normalizedName; } } Boilerplate
  • 19. Ye Olde Logging import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ClassWithLogs { private static Logger log = LoggerFactory.getLogger(ClassWithLogs.class); public String getNormalizedName(Person person) { log.info("getNormalizedName called"); log.debug("Normalizing " + person.toString()); String normalizedName = person.getName().toUpperCase().trim(); log.debug("Normalized name is: " + normalizedName); return normalizedName; } } Eager Evaluation Boilerplate
  • 20. Ye Olde Logging import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ClassWithLogs { private static Logger log = LoggerFactory.getLogger(ClassWithLogs.class); public String getNormalizedName(Person person) { log.info("getNormalizedName called"); log.debug("Normalizing " + person.toString()); String normalizedName = person.getName().toUpperCase().trim(); log.debug("Normalized name is: " + normalizedName); return normalizedName; } } Eager Evaluation Boilerplate
  • 21. Improvement? public class LoggingSample implements Logging { public String getNormalizedName(Person person) { logInfo("getNormalizedName called"); logDebug("Normalizing " + person.toString()); String normalizedName = person.getName().toUpperCase().trim(); logDebug("Normalized name is: " + normalizedName); return normalizedName; } }
  • 22. Improvement? public class LoggingSample implements Logging { public String getNormalizedName(Person person) { logInfo("getNormalizedName called"); logDebug("Normalizing " + person.toString()); String normalizedName = person.getName().toUpperCase().trim(); logDebug("Normalized name is: " + normalizedName); return normalizedName; } }
  • 23. Improvement? public class LoggingSample implements Logging { public String getNormalizedName(Person person) { logInfo("getNormalizedName called"); logDebug("Normalizing " + person.toString()); String normalizedName = person.getName().toUpperCase().trim(); logDebug("Normalized name is: " + normalizedName); return normalizedName; } }
  • 25. Java Interface Limitations • No fields allowed
  • 26. Java Interface Limitations • No fields allowed – Need Logger instance
  • 27. Java Interface Limitations • No fields allowed – Need Logger instance – Workaround: getter public interface Logging { Logger logger(); default void logDebug(String msg) { if (logger().isDebugEnabled()) logger().debug(msg); } default void logInfo(String msg) { if (logger().isInfoEnabled()) logger().info(msg); } }
  • 28. Java Interface Limitations • No fields allowed – Need Logger instance – Workaround: getter – But... boilerplate :-( public interface Logging { Logger logger(); default void logDebug(String msg) { if (logger().isDebugEnabled()) logger().debug(msg); } default void logInfo(String msg) { if (logger().isInfoEnabled()) logger().info(msg); } }
  • 29. Java Interface Limitations • No fields allowed – Need Logger instance – Workaround: getter – But... boilerplate :-( • Only public methods – Logging APIs visible! – … as is logger() public interface Logging { Logger logger(); default void logDebug(String msg) { if (logger().isDebugEnabled()) logger().debug(msg); } default void logInfo(String msg) { if (logger().isInfoEnabled()) logger().info(msg); } }
  • 31. And Lazy Evaluation? • Can be implemented with a lambda: import java.util.function.Supplier; default void logDebug(Supplier<String> message) { if (getLogger().isDebugEnabled()) getLogger().debug(message.get()); }
  • 32. And Lazy Evaluation? • Can be implemented with a lambda: import java.util.function.Supplier; default void logDebug(Supplier<String> message) { if (getLogger().isDebugEnabled()) getLogger().debug(message.get()); } • But there’s boilerplate at the call site: logDebug(() -> "Normalizing " + person.toString());
  • 33. Scala Traits trait Logging { private val logger = LoggerFactory.getLogger(getClass) protected def logWarn(msg: => String) = if (logger.isWarnEnabled) logger.warn(msg) protected def logDebug(msg: => String) = if (logger.isDebugEnabled) logger.debug(msg) }
  • 34. Scala Traits • Allow fields trait Logging { private val logger = LoggerFactory.getLogger(getClass) protected def logWarn(msg: => String) = if (logger.isWarnEnabled) logger.warn(msg) protected def logDebug(msg: => String) = if (logger.isDebugEnabled) logger.debug(msg) }
  • 35. Scala Traits • Allow fields • Participate in lifecycle trait Logging { private val logger = LoggerFactory.getLogger(getClass) protected def logWarn(msg: => String) = if (logger.isWarnEnabled) logger.warn(msg) protected def logDebug(msg: => String) = if (logger.isDebugEnabled) logger.debug(msg) }
  • 36. Scala Traits • Allow fields • Participate in lifecycle • Support visibility trait Logging { private val logger = LoggerFactory.getLogger(getClass) protected def logWarn(msg: => String) = if (logger.isWarnEnabled) logger.warn(msg) protected def logDebug(msg: => String) = if (logger.isDebugEnabled) logger.debug(msg) }
  • 37. Scala Traits • Allow fields • Participate in lifecycle • Support visibility • Multiple inheritance! trait Logging { private val logger = LoggerFactory.getLogger(getClass) protected def logWarn(msg: => String) = if (logger.isWarnEnabled) logger.warn(msg) protected def logDebug(msg: => String) = if (logger.isDebugEnabled) logger.debug(msg) }
  • 38. Scala Traits • Allow fields • Participate in lifecycle • Support visibility • Multiple inheritance! • By Name eval trait Logging { private val logger = LoggerFactory.getLogger(getClass) protected def logWarn(msg: => String) = if (logger.isWarnEnabled) logger.warn(msg) protected def logDebug(msg: => String) = if (logger.isDebugEnabled) logger.debug(msg) }
  • 41. Type Inference • …the analysis of a program to infer the types of some or all expressions, usually at compile time…
  • 42. Type Inference • …the analysis of a program to infer the types of some or all expressions, usually at compile time… • A balance between Compile Time Safety and Verbosity
  • 44. Java’s Type Inference • Generics class ClassWithGenerics { <T> void generic(T param) { println(someParameter); } } ... generic(“some param”) generic(5)
  • 45. Java’s Type Inference • Generics • Project Coin class ClassWithGenerics { <T> void generic(T param) { println(someParameter); } } ... generic(“some param”) generic(5) Map<String, Int> keyCounter = new HashMap<>();
  • 48. Scala’s Type Inference • Generics • Local variables
  • 49. Scala’s Type Inference • Generics • Local variables • Method return values
  • 50. LET’S DIVE INTO SOME CODE
  • 53. Java’s Switch Statement • Switch statement is incredibly limited – Only supports primitives (and strings) – No arbitrary expressions (e.g. guards) – No result values
  • 54. Java’s Switch Statement • Switch statement is incredibly limited – Only supports primitives (and strings) – No arbitrary expressions (e.g. guards) – No result values • Workarounds are ugly – Nested control structures – Encoding enums instead of using types
  • 55. Pattern Matching • Pattern matching in Scala:
  • 56. Pattern Matching • Pattern matching in Scala: – Allows arbitrary types
  • 57. Pattern Matching • Pattern matching in Scala: – Allows arbitrary types – Supports guards
  • 58. Pattern Matching • Pattern matching in Scala: – Allows arbitrary types – Supports guards – Checks for exhaustiveness
  • 59. Pattern Matching • Pattern matching in Scala: – Allows arbitrary types – Supports guards – Checks for exhaustiveness – User-extensible
  • 60. Pattern Matching • Pattern matching in Scala: – Allows arbitrary types – Supports guards – Checks for exhaustiveness – User-extensible – Ubiquitous
  • 61. LET’S DIVE INTO SOME CODE
  • 63. Passing Class info (generics)
  • 64. Passing Class info (generics) • Java’s idiom is passing Class<T> clazz around
  • 65. Passing Class info (generics) • Java’s idiom is passing Class<T> clazz around • Scala supports implicit parameters – These are filled in by the compiler – Well-defined rules for implicit search
  • 67. Enhancing third party code • Java’s idiom is verbose wrapper methods
  • 68. Enhancing third party code • Java’s idiom is verbose wrapper methods • Scala supports implicit methods – Verified at compile time
  • 69. LET’S DIVE INTO SOME CODE
  • 73. Scala’s Relevance • Post Java 8 • Towards Java 9 ✔
  • 74. Scala’s Relevance • Post Java 8 • Towards Java 9 ✔ ✔
  • 75. Scala’s Relevance • Post Java 8 • Towards Java 9 • Java 10 ✔ ✔
  • 76. Scala’s Relevance • Post Java 8 • Towards Java 9 • Java 10 ✔ ✔ ?
  • 78. WE’RE DONE HERE! Thank you for listening @ittaiz http://il.linkedin.com/in/ittaiz Sample Code: https://github.com/ittaiz/scala-and-java8

Notas del editor

  1. Image: http://searchengineland.com/figz/wp-content/seloads/2015/06/evolution-seo-marketer-ss-1920.jpg
  2. Photo source: https://flic.kr/p/3xcrQG
  3. Photo source: https://flic.kr/p/3xcrQG
  4. Photo source: https://flic.kr/p/3xcrQG
  5. Photo source: https://flic.kr/p/3xcrQG