Tuesday, June 23, 2009

#osb09 Scala Less is More

I had a great time at #osb09 and had the pleasure of giving a presentation on Scala for Recovering Java developers. Here are some notes from that talk The code to go along with this is in my github account at here

Why Scala?

What is Scala? Scala is one part scripting language, 1 part functional language, and and a big heaping helping of Java done right.
Scala runs on the JVM and the CLR. It incorporates the best features of functional and object oriented paradigms to create a rich, scalable language that works well to create small apps that scale to become massive apps.

Scala has a rich type inference algorithm that allows the programmer to express what they want to with out allot of the ceremony of type annotations and boilerplate code that is so common in Java.

Reduction in lines of code of up to 2x is very common when compared to Java Loc

Scala is byte-code compatible with java and can make calls into java code very easily, this gets you access to all of the great java libraries

Scala has a very strong actor based concurrency library that makes writing concurrent programs easier and makes reasoning about their execution much simpler

Scala is starting to see wide spread adoption: Twitter, LinkedIn, Stanford, Berkley,

First Stop

Unlike Java, Scala has no primitives, everything is an object so Scala can be thought of as a more pure OO language then Java.

All “operators” are method invocations and as such most can be overridden, no true operators

Most of the types in Scala are familiar to Java programmers, types such as Int, Double, Boolean, String, Array, Map

Variables are defined with the val or var syntax, var is like a regular Java variable, Val is similiar to a java final declaration and can not be modified after it is assigned. Idiomatic Scala prefers the use of vals as Mutable state can become a bit of a liability when you start to get parrellel programs.

== Unlike Java == in Scala compares object equality and not reference equality

Methods are defined with the keyword def, if a method does not have an equals it returns unit

Return can be left off and the last expression will be returned unless the method returns unit, Unit is the scala equivalent of void

Scala has an option type to indicate a method that can return Null, in this it returns Some() or None

Code defined in a class or object outside of a method is run as the constructor for the class

Scala has an interactive terminal that makes it easy to try out new functions and libraries

Scala has Traits, also referred to as Mixins, these are like Java interfaces that can contain behavior and state. These are incredibly useful for writing DRY code and for creating rich interfaces. You can write a rich trait and mix it into several classes, then you decide you want to add more behavior to the trait, this is no problem in Scala the classes that mix in the trait do not need to be changed, they get the new behavior automatically, unlike in Java’s interfaces where you would have to implement the behavior in each class that implemented the method.

Traits differ from interfaces in two key ways:
First, a trait cannot have any class parameters, or constructor variables
Secondly traits method calls are dynamically bound not statically like a concrete class, for instance super.toString will get bound to the current super class of the trait, this makes traits stackable

Code Already

Here we have a very simple Java class called myjavaclass with a constructor that takes two parameters and has a getter and a setter for the third.

Here is the same class defined in Scala, The parameters after the class name become the consturctor and implement private members of index and name. The member who will generate getters and setters for itself. As you can see the scala implementation is much simpler and cleaner then the Java one, as well as being 16 lines shorter.

The usages are very similar except when you want to access who in Scala you can just use the dot notation property name and it will return the value or if you assign a value to it will use the setter.

Functional Scala

Scala is also a functional language with support for Higher order functions, Tuples, Closures, Pattern Matching, and functional data collections.

Pattern matching in scala is like Java switch expression on steroids, it is also an expression so it will return the value of the match. Here is a simple example of pattern matching that takes the scala class Any. Scala can match on Constants, Case Classes/Objects Variable patterns, and Wild Cards

Case classes generate == and hashcode for you.

The most commonly used data collection in Scala is the list, list can be constructed in several ways the can be consed together with the cons(::) operator or they can use their shortcut constructor

The _ is a place holder keyword and can be used when a value will appear only once in the expression, or as a parameter list in a partially applied function.

Duck Typing

Scala allows you to define implicit conversions from one type to another and the compiler will insert these for you to try to solve type problems.

This can be used to add new methods to an existing library,

Structural typing allows you to create functions that specify a structural type that they accept as opposed to a concrete type.

Scala also provides view bounds which allow you to accept parameters as long as they conform to a specified trait/interface

In this maxList function we can take a list of anything as long as any mixes in the ordered trait.

note: upper bounds : this object is a, view bounds this object can be treated as a


Moore’s law has run out, we are seeing machines with 4, 8 and even 36 cores in productions systems today and that number is climbing rapidly, Any speed improvements from here forward are going to come from us as programmers taking advantage of the hardware as opposed to an increase in clock speed.

What are actors? An actor is simply a lightweight process that executes a lambda. Actors should never share state and thus never need to compete for locks for access to shared data. Instead, actors share data by sending messages that are immutable. Immutable data cannot be modified, so reads do not require a lock.

So how does an Actor get Data?
The actor based concurrency model is based on message passing, each actor has its own internal mailbox of messages that it has received, each time through loop it will grab a message of the box and attempt to handle it. Messages can be processed in two different ways in Scala, the fist is with the receive method that processes the message and then returns some value, or with react that does not return a value and therefor does not need to preserve the call stack. The use of react is highly encouraged in Scala as a well structured program using react can be run in a single core.

Because messages can be delivered at any given point in time (and more importantly) may come with considerable delay between sending and receiving, take care to make sure that messages carry all the state they might need in order to be handled correctly.

Ensure that actors do not block, if they need to wait they should have an internal actor that waits and then calls them back to continue the processing

No comments:

Post a Comment