A teaser talk for Scala newbies, introducing five basic elements that (in my opinion) make the transition from Java to Scala a no-brainer.
Given at the 7th JJTV (Israeli Java/JVM user group) tool night, July 2nd, 2013.
Tomer GabelConsulting Engineer at Substrate Software Services
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 )
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