Top 10 Reasons Java Programs Envy Scala

A whirlwind tour through 10 productivity-increasing features of Scala that aims to inspire Java developers to jump on the Scala bandwagon for their own coding pleasure. »
Graham Lea

Since late 2009
Blog: 'Graham Hacking Scala'
Code: SodaTest 
11 years Java development
distributed, enterprise systems                                                              (and associated web stuff)
Tyro Payments in Sydney since 2007
JetBrains Development Academy Member
Top 10 Reasons 
Java Programs
Envy Scala
#1 - Type Inference
#2 - Less Syntax
#3 - Collection Tricks
#4 - Java Interoperability
#5 - Pimp My Library
#6 - DIY Operators
#7 - Pattern Matching
#8 - Named & Default Parameters
#9 Multiple Inheritance of Traits
#10 - Simplified Concurrency
Alternative Title:
Top 10 Reasons
Scala is faster to write and
smaller to read than Java
Mypoorbrain @ flickr
Alternative Title:
Top 10 Features
missing from Java
but present in almost every other modern language
Alternative Title:
Top 10 Scala features
that Scala hobbyists whinge about
not being able to use at their Java day job
unwiederbringlichbegangenes @ flickr
Graham Lea
Scala Hobbyist
with a Java day job
Declarations
Java
Scripting
Languages
Scala 
Type-Safety
Verbose<Verbose> verbose = new Verbose<Verbose>()
Catches type errors before
code can even run
Compile-time safety
Succinct
Run-time checking
"Catches" errors 
in Production
Me no like
Succinct
Compile-time safety
meaningfulName  =  value.with(meaning) and !noise
No Compromise
Computers don't need to be told everything.
They can figure a lot of things out for themselves.
(with type inference)
Java : Explicit Types
Scala : Inferred Types
Look, Ma! No Types!
But still type-safe
(Actually, the trade-off is that compiling is slower)
Sometimes it's best to let all the details be
handled by someone else.
Java
Scala
Procedural
Semi-colons optional
     (except where ambiguous)
parentheses optional
'val' same as 'final'
this should be your first choice
(for zero- and one-argument functions)
Defining Classes
Java
Scala
Class declarations
Constructors
Fields
Accessors
Mutators
Everything is public by default
        (classes, properties and functions)
Declarations include the constructor
Properties: just name, type and mutability ('val' or 'var')
Private fields with public accessors and mutators (for vars) are auto-generated and can be overridden.
Introduce Java programmers to 10 simple Scala features that will make them more productive.
Get Java programmers switching to Scala.
(For their own benefit!)
Aim:
Ulterior Motive :
dereference operator ('.') optional
Combine these two, and: 
     functions appear like operators,
     parentheses are mainly used for precedence
(Yes, this code does everything the Java code does.)
Closures
Java
Scala
( or Function Objects, Fuction Pointers, Functors, etc. )
This is a closure in Java
This is a function object type in Java
This is a function object type in Scala
This is a closure in Scala
The Scala language has first-class functions
But the JVM doesn't !!
So it's actually all smoke, mirrors
and syntactic sugar.
The Type:   (Int) => Int

          is just shorthand for the trait:

                      scala.Function1[Int, Int]
The Closure:   { _ * 2 - 1 }

          is just shorthand for:

                      new Function1[Int, Int] {
                          def apply(n: Int): Int = {
                              n * 2 - 1
                          }
                      }
Creating Collections
Java
Scala
Static imports have made
                   some things easier
Other trivial things are
still a bit non-trivial
(list concatenation)
Simple things are simple to do
When you have a lot of things to deal with,
it's nice if dealing with lots of things is easy to do.
You can achieve something similar in Java by creating 
your own static methods and importing them:

    map(entry("One", 1), entry("Two", 2), entry("Three", 3))
Filtering Collections
Java
Scala
This is the predicate.
This is the operation.
Mapping Collections
Java
Scala
The "WHAT"
The "HOW"
The "WHAT"
The "HOW"
Summing Numbers
Java
Scala
!!!!!
Seamless 
Extending Others' Classes
Java
Make maths look like maths
Java
Scala
Choosing a value: Switch vs Match
Java
Scala
Java
Scala
Deconstructing Your Own Classes
Java
Scala
Named: Every Function is a Builder
Java (Vanillla)
Scala
Mix-Ins without Delegation
Java
Scala
Actors: Asynchronous Agents
Java
Scala
Static method definitions...
Scala
... imported statically for brevity
End Result: convenient, but still feels like *Util class
Implicit conversion functions
Wrapper types with new functions
+
End result: existing classes appear to have new, advanced behaviour
Some things are just made to do brilliant work together.
Why shouldn't your code look this good?
Just try not to go overboard.

Too many extensions may indicate the need for a 
different tool altogether.
by twm1340 @ flickr
Doesn't look much like what you
learnt in year 9 math class.
Pimping BigDecimal !
Much more natural
Sometimes symbols are the most effective way to communicate
Martin Odersky's original post about the pattern:
http://www.artima.com/weblogs/viewpost.jsp?thread=179766
Quicker to write
Easier to understand
Note: You don't write this bit in every class where you want to use operators. You write it once and import it where necessary.
That's DIY + DRY
Less repeating yourself
(Like FIT, but with spreadsheets and Scala instead of HTML and Java)
Available on:
Spreadsheet-driven integration testing
http://grahamhackingscala.blogspot.com/
switch is procedural:
     each case is a list of statements
          to get a value out, you have to assign it
match is functional:
     every case has a value
          most cases are expressions not statements
match returns a result!
Being good at matching can make you a lot of money
Testing & Splitting a List
Inspecting the collection contents
Deconstructing the collection
Inspecting the object
Deconstructing the object
If you're not clear on your identity, you can cause a lot of damage.
Java (Builder)
Too cryptic
Too verbose
Not reusable
Not only is this a lot of code,
it's completely coupled to,
(and derivable from) Customer.
Nothing special here. 
Every function can be used this way.
Defaults: The Overload Killer
Java :
Scala :
Overload to provide defaults
Specify defaults in signature
Extra
lines
just
to
specify 
default
values.
Some combinations can't have defaults
Simple & clear
Every constructor is a builder!!!
Combining existing components can be really useful
Complete, generic implementation.
       Prime candidate for re-use.
Delegation noise required to
actually make use of it.
Complete, generic implementation.
No noise required.
Behaviour is mixed in at compile-time.
Everyone wishes they could multi-task simply.
Threading "boilerplate"
Threading boilerplate
Parallel Collections
Scala
Calling thread continues 
on with other work...
Calling thread waits for 
completion of computation...
One-word parallel processing !
Feeling envious? Time to learn Scala.
Use named parameters
to resolve ambiguity
This is the predicate.
This is the operation.
google:
Graham's guide to learning scala
End result:
   A list of simple patterns
End result:
   A complex tree 
      of decision logic
2 cpu machine = 
2 items processed in parallel
soundcloud.com/grahamlea
Audio of me presenting at
ScalaSyd, October 2011

Loading comments...

Please log in to add your comment.

Report abuse