Ponies and Unicorns With Scala

Tomer Gabel
Tomer GabelConsulting Engineer at Substrate Software Services
Ponies and
unicorns with
A JJTV Tools Night Presentation
Tomer Gabel, Wix.com
You want these
• Type inference
• Closures
• Options
• Traits
• Collection Framework
Type Inference
#1
Saves buttloads of code!
final Map<String, String> parameters =
new HashMap<String, String>();
parameters.put( “param1”, “value” );
parameters.put( “param2”, “value” );
val parameterMap = Map( “param1” → “value”,
“param2” → “value” )
Type inference
• Pervasive!
– Locals
– Parameters
– Type parameters
– … everything other than formal
definitions, really!
Closures
#2
Simply put…
• Short-hand for unnamed functions
val isEven = ( v: Int ) => v % 2 == 0
• Can be passed around as parameters
def filterBy( predicate: Int => Boolean )
Functional building block
• All Scala collections (of T) support:
– Filtering by predicate (T=>Boolean)
– Finding a value by predicate
– Mapping by transformation (T=>R)
– Sorting by an arbitrary function
Compare…
List<Integer> list = …;
List<Integer> onlyEvens =
filter( list, new Predicate<Integer>() {
public boolean test( Integer value ) {
return value % 2 == 0;
}
} );
val list: List[ Int ] = …;
val onlyEvens = list.filter( _ % 2 == 0 )
Callbacks
// Runs a background process
def invokeProcess( command: String,
onExit: Int => Unit )
// Call site:
invokeProcess( “tar –cvjf backup.tar.bz2 *”,
exitCode =>
if ( exitCode <> 0 )
error( “Failed to generate backup!” )
)
Options
#3
NPEs are crap
String lower( String v ) {
if ( v == null )
return null;
else
return v.toLowerCase();
}
Does not document intent
Redundant
Always needs checking
NPEs are still crap
• In Scala, nulls are a code smell
• … except for legacy interop
def lower( v: Option[ String ] ) =
v.map( _.toLowerCase )
Clear semantics
Explicit access
Options are great!
• Loads of helpers:
– optional.getOrElse( “default value” )
– optional.orElse( anotherOption )
– optional.orNull // Legacy helper
• Just another collection!
– def lookup( id: Long ): Option[ User ] = …
for ( id <- idList; user <- lookup( id ) )
println( user.name )
Traits
#4
Multiple inheritance
• Traits are like Java interfaces
• … with optional implementation
• Useful for:
– Helpers
– Functional composition
– Good old interface declarations
Boilerplate 101
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class MyClass {
private static Logger log =
LoggerFactory.getLogger( MyClass.class );
void myMethod() {
log.info( “Some message” );
}
}
x1000 classes
Boilerplate!
The Logging trait
import org.slf4j.LoggerFactory
trait Logging {
private val log =
LoggerFactory.getLogger( this.getClass );
def info( s: => String ) {
if( log.isInfoEnabled ) log.info( s );
}
def trace( s: => String ) { … }
// etc.
}
A better way
• Now you can do..
class MyClass extends Logging {
def myMethod() {
…
info( “Some message” )
}
}
Functional composition
• Consider collections…
– Iterable[T] provides iteration
– Seq[T] implies ordering and indexing
– Vector[T] implements Seq[T]
• map, filter, foreach implemented by
Iterable[T]
• … Seq adds indexOf, slice, sortBy…
• … Vector re-implements for performance!
Collection Framework
#5
It will rock your world
Given the following:
case class Person( name: String, age: Int )
val people: List[ Person ] = …
You can now do…
val firstTen = people.take( 10 )
val onlyMinors = people.filter( _.age < 18 )
val nameSet = people.map( _.name ).toSet
… and then some
That was just the tip of the iceberg.
val sorted = people.sortBy( _.age )
val index = people.groupBy( _.name.head )
val pairs = people.sliding( 2, 2 )
val ( minors, adults ) =
people.partition( _.age < 18 )
Maps
• Maps are also collections
• … and can be used as lookup functions
val peopleById: Map[ Long, Person ] = …
def getPeople( ids: List[ Long ] ) =
ids map peopleById
Over and out
• Thank you for your time!
• Questions and comments welcome!
– tomer@tomergabel.com
– http://www.tomergabel.com
1 of 25

More Related Content

What's hot(20)

Scala fundamentalsScala fundamentals
Scala fundamentals
Alfonso Ruzafa1.4K views
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel3.7K views
First-Class PatternsFirst-Class Patterns
First-Class Patterns
John De Goes3.2K views
Scala jeffScala jeff
Scala jeff
jeff kit1.3K views
Demystifying Shapeless Demystifying Shapeless
Demystifying Shapeless
Jared Roesch8.4K views
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
fanf423.4K views
Practically FunctionalPractically Functional
Practically Functional
djspiewak1.5K views
10 Things I Hate About Scala10 Things I Hate About Scala
10 Things I Hate About Scala
Meir Maor3K views
Scala IntroScala Intro
Scala Intro
Alexey (Mr_Mig) Migutsky7.6K views
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)
Eduard Tomàs1.2K views
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight12.1K views
Scala coated JVMScala coated JVM
Scala coated JVM
Stuart Roebuck999 views
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
Tim Underwood23.1K views
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko7.4K views

Similar to Ponies and Unicorns With Scala(20)

Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
Baishampayan Ghose686 views
Scala for curiousScala for curious
Scala for curious
Tim (dev-tim) Zadorozhniy514 views
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & Scala
Martin Ockajak114 views
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
Eric Pederson967 views
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
Martin Ockajak81 views
C# programming C# programming
C# programming
umesh patil434 views
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
Santosh Rajan10.4K views
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
Stuart Roebuck1.1K views
Angular2 for BeginnersAngular2 for Beginners
Angular2 for Beginners
Oswald Campesato1K views
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
shinolajla10.1K views
Scala ntnuScala ntnu
Scala ntnu
Alf Kristian Støyle493 views
Unraveling the mystery of monadsUnraveling the mystery of monads
Unraveling the mystery of monads
Faisal Waris2.6K views
Compiler Design Tutorial Compiler Design Tutorial
Compiler Design Tutorial
Sarit Chakraborty6.4K views
Clojure introClojure intro
Clojure intro
Basav Nagur1.4K 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
Java 8 and Beyond, a Scala StoryJava 8 and Beyond, a Scala Story
Java 8 and Beyond, a Scala Story
Tomer Gabel747 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
Scala in the WildScala in the Wild
Scala in the Wild
Tomer Gabel2.8K 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
5 Bullets to Scala Adoption5 Bullets to Scala Adoption
5 Bullets to Scala Adoption
Tomer Gabel2.7K 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
Maven for DummiesMaven for Dummies
Maven for Dummies
Tomer Gabel6.3K 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
ChatGPT and AI for Web DevelopersChatGPT and AI for Web Developers
ChatGPT and AI for Web Developers
Maximiliano Firtman161 views
ThroughputThroughput
Throughput
Moisés Armani Ramírez31 views
CXL at OCPCXL at OCP
CXL at OCP
CXL Forum203 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
Web Dev - 1 PPT.pdfWeb Dev - 1 PPT.pdf
Web Dev - 1 PPT.pdf
gdsczhcet49 views

Ponies and Unicorns With Scala

  • 1. Ponies and unicorns with A JJTV Tools Night Presentation Tomer Gabel, Wix.com
  • 2. You want these • Type inference • Closures • Options • Traits • Collection Framework
  • 4. Saves buttloads of code! final Map<String, String> parameters = new HashMap<String, String>(); parameters.put( “param1”, “value” ); parameters.put( “param2”, “value” ); val parameterMap = Map( “param1” → “value”, “param2” → “value” )
  • 5. Type inference • Pervasive! – Locals – Parameters – Type parameters – … everything other than formal definitions, really!
  • 7. Simply put… • Short-hand for unnamed functions val isEven = ( v: Int ) => v % 2 == 0 • Can be passed around as parameters def filterBy( predicate: Int => Boolean )
  • 8. Functional building block • All Scala collections (of T) support: – Filtering by predicate (T=>Boolean) – Finding a value by predicate – Mapping by transformation (T=>R) – Sorting by an arbitrary function
  • 9. Compare… List<Integer> list = …; List<Integer> onlyEvens = filter( list, new Predicate<Integer>() { public boolean test( Integer value ) { return value % 2 == 0; } } ); val list: List[ Int ] = …; val onlyEvens = list.filter( _ % 2 == 0 )
  • 10. Callbacks // Runs a background process def invokeProcess( command: String, onExit: Int => Unit ) // Call site: invokeProcess( “tar –cvjf backup.tar.bz2 *”, exitCode => if ( exitCode <> 0 ) error( “Failed to generate backup!” ) )
  • 12. NPEs are crap String lower( String v ) { if ( v == null ) return null; else return v.toLowerCase(); } Does not document intent Redundant Always needs checking
  • 13. NPEs are still crap • In Scala, nulls are a code smell • … except for legacy interop def lower( v: Option[ String ] ) = v.map( _.toLowerCase ) Clear semantics Explicit access
  • 14. Options are great! • Loads of helpers: – optional.getOrElse( “default value” ) – optional.orElse( anotherOption ) – optional.orNull // Legacy helper • Just another collection! – def lookup( id: Long ): Option[ User ] = … for ( id <- idList; user <- lookup( id ) ) println( user.name )
  • 16. Multiple inheritance • Traits are like Java interfaces • … with optional implementation • Useful for: – Helpers – Functional composition – Good old interface declarations
  • 17. Boilerplate 101 import org.slf4j.Logger; import org.slf4j.LoggerFactory; class MyClass { private static Logger log = LoggerFactory.getLogger( MyClass.class ); void myMethod() { log.info( “Some message” ); } } x1000 classes Boilerplate!
  • 18. The Logging trait import org.slf4j.LoggerFactory trait Logging { private val log = LoggerFactory.getLogger( this.getClass ); def info( s: => String ) { if( log.isInfoEnabled ) log.info( s ); } def trace( s: => String ) { … } // etc. }
  • 19. A better way • Now you can do.. class MyClass extends Logging { def myMethod() { … info( “Some message” ) } }
  • 20. Functional composition • Consider collections… – Iterable[T] provides iteration – Seq[T] implies ordering and indexing – Vector[T] implements Seq[T] • map, filter, foreach implemented by Iterable[T] • … Seq adds indexOf, slice, sortBy… • … Vector re-implements for performance!
  • 22. It will rock your world Given the following: case class Person( name: String, age: Int ) val people: List[ Person ] = … You can now do… val firstTen = people.take( 10 ) val onlyMinors = people.filter( _.age < 18 ) val nameSet = people.map( _.name ).toSet
  • 23. … and then some That was just the tip of the iceberg. val sorted = people.sortBy( _.age ) val index = people.groupBy( _.name.head ) val pairs = people.sliding( 2, 2 ) val ( minors, adults ) = people.partition( _.age < 18 )
  • 24. Maps • Maps are also collections • … and can be used as lookup functions val peopleById: Map[ Long, Person ] = … def getPeople( ids: List[ Long ] ) = ids map peopleById
  • 25. Over and out • Thank you for your time! • Questions and comments welcome! – tomer@tomergabel.com – http://www.tomergabel.com