Java 8 and Beyond, a Scala Story

Tomer Gabel
Tomer GabelConsulting Engineer at Substrate Software Services
Java 8 and Beyond,
a Scala Story
Tomer Gabel, April 2016
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
• Showcase!
– Traits
– Pattern matching
– Implicits
The Java-Scala gap
Historically (pre Java 8)
• Type inference
• Lambdas
• Traits
• Collections library
• DSLs
• Implicits
The Java-Scala gap
Currently (with Java 8)
• Type inference
• Lambdas
• Traits
• Collections library
• DSLs
• Implicits
There’s So Much More…
For-comprehensions
Flexible scoping
Built-in tuples
Higher-kinded types
Implicit conversions
Declaration-site
variance
(Partial) Functions
Bottom types
Structural types
Type members
Path-dependent types
Macros
RIGHT.
WHY SHOULD YOU CARE?
SHOWCASE #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;
}
}
Eager
Evaluation
Boilerplate
Improvement?
public class LoggingSample implements Logging {
public String getNormalizedName(Person person) {
info("getNormalizedName called");
debug("Normalizing " + person.toString());
String normalizedName =
person.getName().toUpperCase().trim();
debug("Normalized name is: " + normalizedName);
return normalizedName;
}
}
Java Interface Limitations
• No state allowed
– Need Logger instance
– Workaround: getter
– But... boilerplate :-(
• Only public methods
– Logging APIs visible!
– … as is logger()
public interface Logging {
Logger logger();
default void debug(String msg) {
if (logger().isDebugEnabled())
logger().debug(msg);
}
default void info(String msg) {
if (logger().isInfoEnabled())
logger().info(msg);
}
}
And Lazy Evaluation?
• Can be implemented with a lambda:
import java.util.function.Supplier;
default void debug(Supplier<String> message) {
if (getLogger().isDebugEnabled())
getLogger().debug(message.get());
}
• But there’s boilerplate at the call site:
debug(() -> "Normalizing " + person.toString());
Scala Traits
• Allow state
• Participate in
lifecycle
• Support
visibility
• Multiple
inheritance!
trait Logging {
private val logger =
LoggerFactory.getLogger(getClass)
protected def warn(msg: => String) =
if (logger.isWarnEnabled)
logger.warn(msg)
protected def debug(msg: => String) =
if (logger.isDebugEnabled)
logger.debug(msg)
}
SHOWCASE #2:
PATTERN MATCHING
Switcheroo
• 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:
– Allows arbitrary types
– Supports guards
– Checks for
exhaustiveness
– User-extensible
– Ubiquitous
ARE YOU READY FOR CODE?
SHOWCASE #3:
IMPLICITS
Serialization in a Nutshell
• Break compound
type into
components
Reflection
• Iterate over
components
• Dispatch by type
Dispatch
• Make your
customers happy
• Save the world
• Adopt a puppy
Profit
Right. So?
• Jackson uses runtime
reflection
– Hard to predict
– Lossy (e.g. erasure)
• Pluggable via
modules
– Easy to forget
– Test to avoid mistakes
A Better Way
• Scala supports implicit parameters
– These are filled in by the compiler
– Well-defined rules for implicit search
• This lets you define type classes:
trait Serializer[T] {
def serialize(value: T): JsonValue
def deserialize(value: JsonValue): Try[T]
}
Composition
• Type classes are resolved recursively
• You can encode dependencies:
– If Serializer[T] is known, you can always
handle Option[T]
– Same principle applies to maps, sequences
etc.
• The compiler handles wiring for you
– To an arbitrary level of nesting!
How Is That Better?
• Performance
– No reflective access
– No runtime codegen
• Reliability
– Missing serializer =
compile-time error
– Lossless
– No spurious tests
WE’RE DONE HERE!
… AND YES, WE’RE HIRING :-)
Thank you for listening
tomer@tomergabel.com
@tomerg
http://il.linkedin.com/in/tomergabel
Sample Code:
https://github.com/holograph/scala-vs-java8
1 of 24

More Related Content

What's hot(20)

Neo4 + GrailsNeo4 + Grails
Neo4 + Grails
stasimus1.1K views
Concurrency Constructs OverviewConcurrency Constructs Overview
Concurrency Constructs Overview
stasimus1.6K views
Composable Futures with Akka 2.0Composable Futures with Akka 2.0
Composable Futures with Akka 2.0
Mike Slinn4.5K views
JCR - Java Content RepositoriesJCR - Java Content Repositories
JCR - Java Content Repositories
Carsten Ziegeler5.8K views
Scala adoption by enterprisesScala adoption by enterprises
Scala adoption by enterprises
Mike Slinn8K views
Ruby on the JVMRuby on the JVM
Ruby on the JVM
Kresten Krab Thorup658 views
Sbt, idea and eclipseSbt, idea and eclipse
Sbt, idea and eclipse
Mike Slinn1.4K views
IDLsIDLs
IDLs
Ruslan Shevchenko915 views
Scala Matsuri 2017Scala Matsuri 2017
Scala Matsuri 2017
Yoshitaka Fujii2.1K views
Web development basics (Part-7)Web development basics (Part-7)
Web development basics (Part-7)
Rajat Pratap Singh108 views
Scala final ppt vinayScala final ppt vinay
Scala final ppt vinay
Viplav Jain227 views
Scaling software with akkaScaling software with akka
Scaling software with akka
scalaconfjp3.8K views
Java and the JVMJava and the JVM
Java and the JVM
Manish Pandit592 views
Overview of CoffeeScriptOverview of CoffeeScript
Overview of CoffeeScript
Aniruddha Chakrabarti767 views

Similar to Java 8 and Beyond, a Scala Story

Java 8 featuresJava 8 features
Java 8 featuresOleg Tsal-Tsalko
848 views29 slides
Java ClosuresJava Closures
Java ClosuresBen Evans
1.8K views17 slides
Stairway to scala flyerStairway to scala flyer
Stairway to scala flyerdickwall
457 views11 slides

Similar to Java 8 and Beyond, a Scala Story(20)

Java 8 featuresJava 8 features
Java 8 features
Oleg Tsal-Tsalko848 views
Java ClosuresJava Closures
Java Closures
Ben Evans1.8K views
Reactive Software SystemsReactive Software Systems
Reactive Software Systems
Behrad Zari1K views
Stairway to scala flyerStairway to scala flyer
Stairway to scala flyer
dickwall457 views
Java Serialization Facts and FallaciesJava Serialization Facts and Fallacies
Java Serialization Facts and Fallacies
Roman Elizarov5.9K views
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
Alex Payne40.6K views
Modern Java Concurrency (OSCON 2012)Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)
Martijn Verburg4.2K views
Yes scala can!Yes scala can!
Yes scala can!
amirmoulavi1.4K views
Scala: An experience reportScala: An experience report
Scala: An experience report
Mark Needham1.1K views
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
fanf423.4K views
JavaOne 2011 RecapJavaOne 2011 Recap
JavaOne 2011 Recap
Jim Bethancourt126 views
How Scala promotes TDDHow Scala promotes TDD
How Scala promotes TDD
Shai Yallin4.2K views
JScala. Write your JavaScript in ScalaJScala. Write your JavaScript in Scala
JScala. Write your JavaScript in Scala
Alexander Nemish1.7K views
Typesafe stack - Scala, Akka and PlayTypesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and Play
Luka Zakrajšek3.3K views
Short and fast introduction to ScalaShort and fast introduction to Scala
Short and fast introduction to Scala
Sergi González Pérez409 views
What’s expected in Java 9What’s expected in Java 9
What’s expected in Java 9
Gal Marder404 views
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
Pray Desai3.3K views

More from Tomer Gabel(20)

How shit works: TimeHow shit works: Time
How shit works: Time
Tomer Gabel342 views
How shit works: the CPUHow shit works: the CPU
How shit works: the CPU
Tomer Gabel1.8K views
How Shit Works: StorageHow Shit Works: Storage
How Shit Works: Storage
Tomer Gabel914 views
The Wix Microservice StackThe Wix Microservice Stack
The Wix Microservice Stack
Tomer Gabel1.7K views
Onboarding at ScaleOnboarding at Scale
Onboarding at Scale
Tomer Gabel1.5K views
Put Your Thinking CAP OnPut Your Thinking CAP On
Put Your Thinking CAP On
Tomer Gabel3.5K views
A Field Guide to DSL Design in ScalaA Field Guide to DSL Design in Scala
A Field Guide to DSL Design in Scala
Tomer Gabel6.5K views
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel3.7K views
5 Bullets to Scala Adoption5 Bullets to Scala Adoption
5 Bullets to Scala Adoption
Tomer Gabel2.7K views
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With Scala
Tomer Gabel961 views
Lab: JVM Production Debugging 101Lab: JVM Production Debugging 101
Lab: JVM Production Debugging 101
Tomer Gabel2.1K views
DevCon³: Scala Best PracticesDevCon³: Scala Best Practices
DevCon³: Scala Best Practices
Tomer Gabel3.7K views

Recently uploaded(20)

METHOD AND SYSTEM FOR PREDICTING OPTIMAL LOAD FOR WHICH THE YIELD IS MAXIMUM ...METHOD AND SYSTEM FOR PREDICTING OPTIMAL LOAD FOR WHICH THE YIELD IS MAXIMUM ...
METHOD AND SYSTEM FOR PREDICTING OPTIMAL LOAD FOR WHICH THE YIELD IS MAXIMUM ...
Prity Khastgir IPR Strategic India Patent Attorney Amplify Innovation24 views
ThroughputThroughput
Throughput
Moisés Armani Ramírez31 views
Web Dev - 1 PPT.pdfWeb Dev - 1 PPT.pdf
Web Dev - 1 PPT.pdf
gdsczhcet49 views
ChatGPT and AI for Web DevelopersChatGPT and AI for Web Developers
ChatGPT and AI for Web Developers
Maximiliano Firtman161 views
The Research Portal of Catalonia: Growing more (information) & more (services)The Research Portal of Catalonia: Growing more (information) & more (services)
The Research Portal of Catalonia: Growing more (information) & more (services)
CSUC - Consorci de Serveis Universitaris de Catalunya59 views

Java 8 and Beyond, a Scala Story

  • 1. Java 8 and Beyond, a Scala Story Tomer Gabel, April 2016
  • 2. Preface • Java 8 was released in 2014 • Which begs the question… • Is Scala still relevant? – Yes. – This talk is about convincing you!
  • 3. Quick Agenda • A bit of history – The Java-Scala gap – How Java 8 reduces it – Remaining gaps • Showcase! – Traits – Pattern matching – Implicits
  • 4. The Java-Scala gap Historically (pre Java 8) • Type inference • Lambdas • Traits • Collections library • DSLs • Implicits
  • 5. The Java-Scala gap Currently (with Java 8) • Type inference • Lambdas • Traits • Collections library • DSLs • Implicits
  • 6. There’s So Much More… For-comprehensions Flexible scoping Built-in tuples Higher-kinded types Implicit conversions Declaration-site variance (Partial) Functions Bottom types Structural types Type members Path-dependent types Macros
  • 9. 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
  • 10. Improvement? public class LoggingSample implements Logging { public String getNormalizedName(Person person) { info("getNormalizedName called"); debug("Normalizing " + person.toString()); String normalizedName = person.getName().toUpperCase().trim(); debug("Normalized name is: " + normalizedName); return normalizedName; } }
  • 11. Java Interface Limitations • No state allowed – Need Logger instance – Workaround: getter – But... boilerplate :-( • Only public methods – Logging APIs visible! – … as is logger() public interface Logging { Logger logger(); default void debug(String msg) { if (logger().isDebugEnabled()) logger().debug(msg); } default void info(String msg) { if (logger().isInfoEnabled()) logger().info(msg); } }
  • 12. And Lazy Evaluation? • Can be implemented with a lambda: import java.util.function.Supplier; default void debug(Supplier<String> message) { if (getLogger().isDebugEnabled()) getLogger().debug(message.get()); } • But there’s boilerplate at the call site: debug(() -> "Normalizing " + person.toString());
  • 13. Scala Traits • Allow state • Participate in lifecycle • Support visibility • Multiple inheritance! trait Logging { private val logger = LoggerFactory.getLogger(getClass) protected def warn(msg: => String) = if (logger.isWarnEnabled) logger.warn(msg) protected def debug(msg: => String) = if (logger.isDebugEnabled) logger.debug(msg) }
  • 15. Switcheroo • 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
  • 16. Pattern Matching • Pattern matching in Scala: – Allows arbitrary types – Supports guards – Checks for exhaustiveness – User-extensible – Ubiquitous
  • 17. ARE YOU READY FOR CODE?
  • 19. Serialization in a Nutshell • Break compound type into components Reflection • Iterate over components • Dispatch by type Dispatch • Make your customers happy • Save the world • Adopt a puppy Profit
  • 20. Right. So? • Jackson uses runtime reflection – Hard to predict – Lossy (e.g. erasure) • Pluggable via modules – Easy to forget – Test to avoid mistakes
  • 21. A Better Way • Scala supports implicit parameters – These are filled in by the compiler – Well-defined rules for implicit search • This lets you define type classes: trait Serializer[T] { def serialize(value: T): JsonValue def deserialize(value: JsonValue): Try[T] }
  • 22. Composition • Type classes are resolved recursively • You can encode dependencies: – If Serializer[T] is known, you can always handle Option[T] – Same principle applies to maps, sequences etc. • The compiler handles wiring for you – To an arbitrary level of nesting!
  • 23. How Is That Better? • Performance – No reflective access – No runtime codegen • Reliability – Missing serializer = compile-time error – Lossless – No spurious tests
  • 24. WE’RE DONE HERE! … AND YES, WE’RE HIRING :-) Thank you for listening tomer@tomergabel.com @tomerg http://il.linkedin.com/in/tomergabel Sample Code: https://github.com/holograph/scala-vs-java8