SlideShare a Scribd company logo
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

More Related Content

PPTX
Ahead-Of-Time Compilation of Java Applications
PPTX
JIT vs. AOT: Unity And Conflict of Dynamic and Static Compilers
PDF
"Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,...
PDF
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
PDF
Bytecode manipulation with Javassist and ASM
PPTX
Java Bytecode For Discriminating Developers - GeeCON 2011
PPTX
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
PPTX
Club of anonimous developers "Refactoring: Legacy code"
Ahead-Of-Time Compilation of Java Applications
JIT vs. AOT: Unity And Conflict of Dynamic and Static Compilers
"Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,...
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
Bytecode manipulation with Javassist and ASM
Java Bytecode For Discriminating Developers - GeeCON 2011
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
Club of anonimous developers "Refactoring: Legacy code"

What's hot (20)

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

Viewers also liked (20)

PPT
09 enllaços i tangencies
ODP
Fotos conica solucio
PDF
040 enllac poligonal
ODP
Inicial 3 b
PDF
Examples of the Human Figure in Art
PPTX
History of figures
PPT
Someone You Know: Final Portrait Project, Glenn Hirsch, Instructor
PDF
037 quadrcula enllaços
PDF
038 apunts enllac
ODP
Inicial 3 c
PPT
History of the figure
PPTX
Cubist self portrait
ODP
010 dibuixen una serp 2
PDF
Figure Drawing Examples
PPT
The figure in art history
PPS
Proportions of the human form
ODP
Inicial 3A
PPT
009 enllaços i tangencies
ODP
La imatge en moviment
PPTX
Proportions of the Figure
09 enllaços i tangencies
Fotos conica solucio
040 enllac poligonal
Inicial 3 b
Examples of the Human Figure in Art
History of figures
Someone You Know: Final Portrait Project, Glenn Hirsch, Instructor
037 quadrcula enllaços
038 apunts enllac
Inicial 3 c
History of the figure
Cubist self portrait
010 dibuixen una serp 2
Figure Drawing Examples
The figure in art history
Proportions of the human form
Inicial 3A
009 enllaços i tangencies
La imatge en moviment
Proportions of the Figure
Ad

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

PPT
Mastering Java ByteCode
PDF
Atlassian Groovy Plugins
PPTX
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
PDF
Aspect oriented programming_with_spring
PPTX
Mastering Java Bytecode - JAX.de 2012
PDF
Appsec usa2013 js_libinsecurity_stefanodipaola
PDF
HashiCorp Vault Plugin Infrastructure
PPTX
Java UNITbgbgbfdbv v bbfbf cvbgfbvc gf 1.pptx
PDF
Instrumentation of Software Systems
PPTX
React inter3
PDF
Eric Lafortune - The Jack and Jill build system
PDF
Java 8 Lambda
PDF
Shiksharth com java_topics
ODP
Lambda Chops - Recipes for Simpler, More Expressive Code
PPTX
Java For beginners and CSIT and IT students
PDF
DIとトレイとによるAndroid開発の効率化
PDF
Java Bytecode for Discriminating Developers - JavaZone 2011
PDF
De Java 8 ate Java 14
PPTX
PPTX
1 java programming- introduction
Mastering Java ByteCode
Atlassian Groovy Plugins
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Aspect oriented programming_with_spring
Mastering Java Bytecode - JAX.de 2012
Appsec usa2013 js_libinsecurity_stefanodipaola
HashiCorp Vault Plugin Infrastructure
Java UNITbgbgbfdbv v bbfbf cvbgfbvc gf 1.pptx
Instrumentation of Software Systems
React inter3
Eric Lafortune - The Jack and Jill build system
Java 8 Lambda
Shiksharth com java_topics
Lambda Chops - Recipes for Simpler, More Expressive Code
Java For beginners and CSIT and IT students
DIとトレイとによるAndroid開発の効率化
Java Bytecode for Discriminating Developers - JavaZone 2011
De Java 8 ate Java 14
1 java programming- introduction

Recently uploaded (20)

PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Approach and Philosophy of On baking technology
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Electronic commerce courselecture one. Pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
A Presentation on Artificial Intelligence
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Encapsulation theory and applications.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPT
Teaching material agriculture food technology
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Cloud computing and distributed systems.
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
DOCX
The AUB Centre for AI in Media Proposal.docx
Digital-Transformation-Roadmap-for-Companies.pptx
Unlocking AI with Model Context Protocol (MCP)
Approach and Philosophy of On baking technology
Mobile App Security Testing_ A Comprehensive Guide.pdf
NewMind AI Monthly Chronicles - July 2025
Electronic commerce courselecture one. Pdf
Building Integrated photovoltaic BIPV_UPV.pdf
A Presentation on Artificial Intelligence
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Review of recent advances in non-invasive hemoglobin estimation
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Encapsulation theory and applications.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Teaching material agriculture food technology
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Cloud computing and distributed systems.
MYSQL Presentation for SQL database connectivity
20250228 LYD VKU AI Blended-Learning.pptx
The AUB Centre for AI in Media Proposal.docx

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

Editor's Notes

  • #2: Image: http://searchengineland.com/figz/wp-content/seloads/2015/06/evolution-seo-marketer-ss-1920.jpg
  • #51: Photo source: https://flic.kr/p/3xcrQG
  • #62: Photo source: https://flic.kr/p/3xcrQG
  • #70: Photo source: https://flic.kr/p/3xcrQG
  • #78: Photo source: https://flic.kr/p/3xcrQG