Friday, July 20, 2012

Scala for Java Refugees Part 3: Methods and Statics

In this series, we’ve already laid the foundations for Scala’s syntax as well as gotten a feel for how some of its object-oriented constructs work.  We haven’t really looked at any of these subjects in-depth however.  Most of our effort has been focused on high-level, flash bang overviews that just get you tasting your way into the language.  This post will go into greater depth regarding method syntax, touch a bit on scopes and attempt to cover how static members work in Scala.  We will also touch on a few gotchas due to “missing” imperative instructions.

Methods Galore

Scala isn’t called a “functional language” just because it’s Turing complete.  Scala has a very powerful and flexible syntax as it relates to methods, both declaration and invocation.  We’ve already seen some basic samples:

class Person {
  def firstName() = {
    var back:String = ...   // read from a database
    back
  }
}
Fairly straightforward.  But this doesn’t really give you the full picture.  In Java for example, you can create methods with different visibilities, modifiers and (oddly enough) return types.  Does Scala support all of this flexibility?
The answer is a qualified “yes”.  Scala does allow for different visibilities on not just methods, but any members.  For example:

class Person {
  private var name = "Daniel Spiewak"
  val ssn = 1234567890    // public constant field
 
  def firstName() = splitName()(0)   // public method
 
  private def splitName() = name.split(" ")    // private method
 
  protected def guessAge() = {
    import Math._
    round(random * 20)
  }
}
At the risk of going on a tangent, it’s worth pointing out the (seemingly) out of place import statement within the guessAge() method.  I mentioned in the first post that Scala’s import is far more powerful than Java’s.  One of its many charms is imparting to the power to import into a specific scope.  The import statement within guessAge() is much like a Java static import statement which only provides access to the Math members within the guessAge() method.  So we couldn’t just make a call to round() from within the splitName() method.  Rubyists can think of it much like the include statement without all of the hassle (it’s not actually including, it’s importing and so eliminating the need for fully-qualified names).
Scala access modifiers are also quite a bit more powerful than Java’s.  For example, protected by default limits access to only subclasses, unlike Java which also allows access to other classes in the same package.  More importantly though, Scala allows the developer to more explicitly specify the scope of the access modifier.  This is accomplished using the modifier[package] notation.  For example:

package com.codecommit.mypackage
 
class MyClass {
  private[mypackage] def myMethod = "test"
}
In this example, myMethod is access-restricted to both the enclosing class and the enclosing package.  Essentially, this is how the Java-style package private modifier can be emulated using Scala.  The protected modifier also allows such visibility qualifiers.  The one restriction here is that the package specified must be an enclosing package.  In the above example, specifying private[com.codecommit.mypackage] is perfectly valid, but private[scala.collection.immutable] would not be correct.
So with the exception of package-private, visibilities work about the same in Scala as they do in Java, both in syntax and function.  Modifiers are really where things get interesting.  Scala has far fewer method modifiers than Java does, primarily because it doesn’t need so many.  For example, Scala supports the final modifier, but it doesn’t support abstract, native or synchronized:

abstract class Person {
  private var age = 0
 
  def firstName():String
  final def lastName() = "Spiewak"
 
  def incrementAge() = {
    synchronized {
      age += 1
    }
  }
 
  @native
  def hardDriveName():String
}
If we were in Java, we would write the above like this:

public abstract class Person {
    private int age = 0;
 
    public abstract String firstName();
 
    public final String lastName() {
        return "Spiewak";
    }
 
    public synchronized void incrementAge() {
        age += 1;
    }
 
    public native String hardDriveAge();
}
Yes, I know it’s more “Scala-esque” to use actors rather than synchronized(), but one step at a time.
You see how Scala keeps with its theme of making the common things concise?  Think about it, almost every method you declare is public, so why should you have to say so explicitly?  Likewise, it just makes sense that methods without a body should be implicitly abstract (unless they’re native).
One very important type-saving feature that you should see in the example above is that Scala doesn’t force you to declare the return type for your methods.  Once again the type inference mechanism can come into play and the return type will be inferred.  The exception to this is if the method can return at different points in the execution flow (so if it has an explicit return statement).  In this case, Scala forces you to declare the return type to ensure unambiguous behavior.
You should also notice that none of the Scala methods actually include a return statement.  This of course seems odd as judging by the Java translation, lastName() should return a String.  Well it turns out that Scala carries a useful shortcut for method returns: the last statement in an expression, be it a scope, a closure or a method becomes its return value.  This convention is also found in languages like Ruby and Haskell.  This example illustrates:

def name() = {
  val name = new StringBuilder("Daniel")
  name.append(" Spiewak");
  name.toString()
}
 
val s = name()
println(s)    // prints "Daniel Spiewak"
Again, in this example the return type of the method is inferred (as String).  We could just as easily have written the name() method as follows, it just would have been less concise.

def name():String = {
  val name = new StringBuilder("Daniel")
  name.append(" Spiewak");
  return name.toString()
}
This “returnless” form becomes extremely important when dealing with anonymous methods (closures).  Obviously you can’t return from a closure, you can only yield, however the principle is the same.  Since closures are often used to reduce code bulk and make certain algorithms more concise, it only makes sense that their return syntax would be as compact as possible:

val arr = Array(1, 2, 3, 4, 5)
val sum = arr.reduceLeft((a:Int, b:Int) => a + b)
 
println(sum)    // 15
In this example we’re passing an anonymous method to the reduceLeft() method within Array.  This method just calls its parameter function repeatedly for each value pair, passing them as the a and b parameters.  Here’s the key part though: our anonymous method adds the two parameters and yields the result back to reduceLeft().  Again, no return statement (or actually, as a closure it would be yield).  Also, we don’t explicitly specify the return type for the closure, it is inferred from our last (and only) statement.

Method Overriding

A very important concept in object-oriented programming is method overriding, where a subclass redefines a method declared in a superclass.  Java’s syntax looks like this:

public class Fruit {
    public int getWorth() {
        return 5;
    }
}
 
public class Apple extends Fruit {
    @Override
    public int getWorth() {
        return 1;
    }
}
Technically, the @Override annotation is optional, but it’s still good practice to use it.  This gives you the compile-time assurance that you actually are overriding a method from a superclass.  In principle, a method declared in a subclass overrides any method in the superclass declared with the exact same signature.  At first glance this seems great, less syntax right?  The problem is when you start dealing with APIs where you’re uncertain if you got the overriding method signature right.  You could just as easily overload the method rather than overriding it, leading to totally different functionality and sometimes hard-to-trace bugs.  This is where @Override comes in.
Scala actually has a bigger problem with method overriding than just signature verification: multiple inheritance.  Multiple inheritance is when one class inherits from more than one superclass.  C++ had this feature years ago, effectively demonstrating how horrible it can really be.  When Gosling laid out the initial spec for Java, multiple inheritance was one of the things specifically avoided.  This is good for simplicity, but it’s sometimes constraining on the power-end of life.  Interfaces are great and all, but sometimes they just don’t cut it.
The key to avoiding ambiguities in the inheritance hierarchy is explicitly stating that a method must override a superclass method.  If that method has the same signature as a superclass method but doesn’t override it, a compile error is thrown.  Add to that significant ordering in the extends/with clauses, and you get a workable multiple-inheritance scheme.  But I’m getting ahead of myself…
Here’s the Fruit example, translated into Scala:

class Fruit {
  def worth() = 5
}
 
class Apple extends Fruit {
  override def worth() = 1
}
Notice that in Scala, override is actually a keyword.  It is a mandatory method modifier for any method with a signature which conflicts with another method in a superclass.  Thus overriding in Scala isn’t implicit (as in Java, Ruby, C++, etc), but explicitly declared.  This little construct completely solves the problems associated with multiple inheritance in Scala.  We’ll get into traits and multiple inheritance in more detail in a future article.
Often times when you override a method, you need to call back to the superclass method.  A good example of this would be extending a Swing component:

class StrikeLabel(text:String) extends JLabel(text) {
  def this() = this("")
 
  override def paintComponent(g:Graphics):Unit = {
    super.paintComponent(g)
 
    g.setColor(Color.RED)
    g.drawLine(1, getHeight() / 2, getWidth() - 1, getHeight() / 2)
  }
}
This component is just a rack-standard JLabel with a red line drawn through its center.  Not a very useful component, but it demonstrates a pattern we see used a lot in Java: delegating to the superclass implementation.  We don’t want to actually implement all of the logic necessary to paint the text on the Graphics context with the appropriate font and such.  That work has already been done for us in JLabel.  Thus we ask JLabel to paint itself, then paint our StrikeLabel-specific logic on top.
As you see in the example, the syntax for making this superclass delegation is almost precisely the same as it is in Java.  Effectively, super is a special private value (much like this) which contains an internal instance of the superclass.  We can use the value just like super in Java to access methods and values directly on the superclass, bypassing our overriding.
That little bit of extra syntax in the extends clause is how you call to a superclass constructor.  In this case, we’re taking the text parameter passed to the default constructor of the StrikeLabel class and passing it on to the constructor in JLabel.  In Java you do the same thing like this:

public class StrikeLabel extends JLabel {
    public StrikeLabel(String text) {
        super(text);
    }
 
    public StrikeLabel() {
        this("");
    }
}
This may seem just a bit odd at first glance, but actually provides a nice syntactical way to ensure that the call to the super constructor is always the first statement in the constructor.  In Java, this is of course compile-checked, but there’s nothing intuitively obvious in the syntax preventing you from calling to the super constructor farther down in the implementation.  In Scala, calling the super constructor and calling a superclass method implementation are totally different operations, syntactically.  This leads to a more intuitive flow in understanding why one can be invoked arbitrarily and the other must be called prior to anything else.

Scala’s Sort-of Statics

Scala is a very interesting language in that it eschews many of the syntax constructs that developers from a Java background might find essential.  This ranges from little things like flexible constructor overloading, to more complex things like a complete lack of static member support.
So in Java, static members are just normal class members with a different modifier.  They are accessed outside of the context of a proper instance using the classname as a qualifier:

public class Utilities {
    public static final String APP_NAME = "Test App";
 
    public static void loadImages() {
        // ...
    }
 
    public static EntityManager createManager() {
        // ...
    }
}
 
System.out.println(Utilities.APP_NAME);
 
Utilities.loadImages();
EntityManager manager = Utilities.createManager();
Scala does support this type of syntax, but under the surface it is quite a bit different.  For one thing, you don’t use the static modifier.  Instead, you declare all of the “static” members within a special type of class which acts as an only-static container.  This type of class is called object.

object Utilities {
  val APP_NAME = "Test App"
 
  def loadImages() = {
    // ...
  }
 
  def createManager():EntityManager = {
    // ...
  }
}
 
println(Utilities.APP_NAME)
 
Utilities.loadImages()
val manager = Utilities.createManager()
The syntax to use these “statics” is the same, but things are quite a bit different in the implementation.  It turns out that object actually represents a singleton class.  Utilities is in fact both the classname and the value name to access this singleton instance.  Nothing in the example above is static, it just seems like it is due to the way the syntax works.  If we port the above class directly to Java, this is what it might look like:

public class Utilities {
    private static Utilities instance;
 
    public final String APP_NAME = "Test App";
 
    private Utilities() {}
 
    public void loadImages() { 
        // ...
    }
 
    public EntityManager createManager() {
        // ...
    }
 
    public static synchronized Utilities getInstance() {
        if (instance == null) {
            instance = new Utilities();
        }
 
        return instance;
    }
}
 
// ...
So Scala provides a special syntax which basically gives us a singleton for free, without all of the crazy syntax involved in declaring it.  This is a really elegant solution to the problems with proper statics.  Since Scala doesn’t actually have static members, we no longer have to worry about mixing scopes, access qualifiers, etc.  It all just works nicely.
But what about mixing static and instance members?  Java allows us to do this quite easily since static is a qualifier, but Scala requires “static” members to be declared in a special singleton class.  In Java, we can do this:

public class Person {
    public String getName() {
        return "Daniel";
    }
 
    public static Person createPerson() {
        return new Person();
    }
}
The solution in Scala is to declare both an object and a class of the same name, placing the “static” members in the object and the instance members in the class.  To be honest, this seems extremely strange to me and is really the only downside to Scala’s singleton syntax:

object Person {
  def createPerson() = new Person()
}
 
class Person {
  def name() = "Daniel"
}
The syntax for using this object/class combination is exactly the same as it would be in Java had we mixed static and instance members.  The Scala compiler is able to distinguish between references to Person the object and references to Person the class.  For example, the compiler knows that we can’t create a new instance of an object, since it’s a singleton.  Therefore we must be referring to the class Person in the createPerson() method.  Likewise, if a call was made to Person.createPerson(), the compiler is more than capable of deducing that it must be a reference to the object Person as there is no way to access a method directly upon a class.  It’s all perfectly logical and consistent, it just strikes the eye funny when you look at it.

Conclusion

And so ends our two part, whirlwind tour of Scala’s object-oriented constructs, methods and statics.  There are of course trivialities along the way which we haven’t covered, but those are easy enough to learn now that you have the basics.  The more interesting syntax is still to come though.  For one thing, we’ve barely scratched the surface of all of the things that you can do with methods.  They don’t call it a “functional” language for nothing!  But in keeping with our goal to represent the imperative side of the Scala language, we’ll save that for later.

(codecommit)
read more...

Scala for Java Refugees Part 2: Basic OOP

In the previous installment, we looked at the basics of Scala syntax and provided some simple conceptual explanations.  Obviously there’s a lot more to this language than what I was able to present in a single (albeit very long) article.  In this post we’re going to examine Scala’s object oriented constructs (classes, objects, methods, etc) and how they compare to Java.

A More Complex Example


package com.codecommit.examples
 
import java.awt.{Color, Graphics}
 
abstract class Shape {
  var fillColor:Color = null
 
  def draw(g:Graphics):Unit
  def area:Double
}
 
class Circle(var radius:Int) extends Shape {
  def draw(g:Graphics):Unit = {
    if (fillColor == null) {
      g.drawOval(0, 0, radius / 2, radius / 2)
    } else {
      g.setColor(fillColor);
      g.fillOval(0, 0, radius / 2, radius / 2)
    }
  }
 
  def area:Double = {
    var back = Math.Pi * radius 
    back * radius
  }
}
 
class Square(var width:Int) extends Shape {
  def draw(g:Graphics):Unit = {
    if (fillColor == null) {
      g.drawRect(0, 0, width, width)
    } else {
      g.setColor(fillColor)
      g.fillRect(0, 0, width, width)
    }
  }
 
  def area:Double = width * width
}
Remember that Scala does not require every public class to be declared in a file of the same name.  In fact, it doesn’t even require every class to be declared in a separate file.  Organizationally, it makes sense for all of these trivial classes to be contained within the same file.  With that in mind, we can copy/paste the entire code snippet above into a new file called “shapes.scala”.
The first thing you should notice about this snippet is the package declaration.  All of these classes are declared to be within the “com.codecommit.examples” package.  If this were Java, we’d have to create a new directory hierarchy to match (com/codecommit/examples/).  Fortunately, Scala saves us work here as well.  We can just store this file right in the root of our project and compile it in place, no hassle necessary.
With that said, it’s still best-practice to separate your packages off into their own directories.  This organization makes things easier to find and eases the burden on you (the developer) in the long run.  And after all, isn’t that what we’re trying to do by looking at Scala in the first place?
To compile this class, we’re going to use the fsc command (short for Fast Scala Compiler).  FSC is one of those brilliant and obvious Scala innovations which allows repeated compilation of Scala files with almost no latency.  FSC almost completely eliminates the compiler startup time incurred by the fact that the Scala compiler runs on the JVM.  It does this by “warm starting” the compiler each time, keeping the process persistent behind the scenes.  Effectively, it’s a compiler daemon, sitting in the background and using almost no resources until called upon.  The command syntax is identical to the scalac command:

fsc -d bin src/com/codecommit/examples/*.scala
This command will compile all of the .scala files within the src/com/codecommit/examples/ directory and place the resultant .class files into bin/.  Experienced Java developers will know the value of this convention, especially on a larger project.  Once again, Scala doesn’t intend to upset all best-practices and conventions established over decades.  Rather, its purpose is to make it easier to do your job by staying out of the way.

First Impressions

Of course, compiling an example doesn’t do us much good if we don’t understand what it means.  Starting from the top, we declare the package for all of the classes within the same file.  Immediately following is a single statement which imports the java.awt.Color and java.awt.Graphics classes.  Notice Scala’s powerful import syntax which allows for greater control over individual imports.  If we wanted to import the entire java.awt package, the statement would look like this:

import java.awt._
In Scala, the _ character is a wildcard.  In the case of an import it means precisely the same thing as the * character in Java:

import java.awt.*;
Scala is more consistent than Java however in that the _ character also serves as a wildcard in other areas, such as type parameters and pattern matching.  But I digress…
Looking further into the code sample, the first declaration is an abstract class, Shape.  It’s worth noting here that the order of declarations in a file does not hold any significance.  Thus, Shape could just as easily have been declared below Circle and Rectangle without changing the meaning of the code.  This stands in sharp contrast to Ruby’s syntax, which can lead to odd scenarios such as errors due to classes referencing other classes which haven’t been declared yet.  Order is also insignificant for method declarations.  As in Java, a method can call to another method even if it is declared above the delegate.

class Person {
  def name() = firstName() + ' ' + lastName()
 
  def firstName() = "Daniel"
  def lastName() = "Spiewak"
}

Properties

Returning to our primary example, the first thing we see when we look at class Shape is the color variable.  This is a public variable (remember, Scala elements are public by default) of type Color with a default value of null.  Now if you’re a Java developer with any experience at all, warning sirens are probably clanging like mad at the sight of a public variable.  In Java (as in other object-oriented languages), best practice says to make all fields private and provide accessors and mutators.  This is to promote encapsulation, a concept critical to object oriented design.
Scala supports such encapsulation as well, but its syntax is considerably less verbose than Java’s.  Effectively, all public variables become instance properties.  You can imagine it as if there were mutator and accessor methods being auto-generated for the variable.  It’s as if these two Java snippets were equivalent (the analog is not precise, it just gives the rough idea):


public class Person {
    public String name;
}


public class Person {
    private String name;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
}
It’s not quite like that, but you get the point of the example.  What’s really happening is we’re taking advantage of the fact that in Scala, variables are actually functions.  It’s a bit of an odd concept to wrap your head around coming from an imperative background, so it’s probably easier just to keep thinking of variables as variables.
Let’s imagine that we’ve got our Shape class and its public variable fillColor.  Down the road we decide that we need to add a check to the mutator to ensure that the color is never red (why, I’m really not sure, but we do).  In Java, this would be impossible because the variable is public and forcing the use of a mutator would change the public class signature.  Thankfully, Scala allows us to easily rewrite that portion of the class without affecting the class signature or any code which actually uses the class:

abstract class Shape {
  private var theFillColor:Color = null
 
  def fillColor = theFillColor
 
  def fillColor_=(fillColor:Color) = {
    if (!fillColor.equals(Color.RED)) {
      theFillColor = fillColor
    } else {
      throw new IllegalArgumentException("Color cannot be red")
    }
  }
}
 
var shape = ...
shape.fillColor = Color.BLUE
var color = shape.fillColor
 
shape.fillColor = Color.RED  // throws IllegalArgumentException
As you can see, the _= method suffix is a bit of magic syntax which allows us to redefine the assignment operator (effectively) for a variable.  Notice from the perspective of the code using Shape, it still looks like a public field.  The code snippet using Shape will work with both the previous and the modified versions of the class.  Think of it, no more get* and set*…  Now you can use public fields with impunity and without fear of design reprisal down the road.
Just to ensure this point is really clear, here’s the analog of the syntax in Ruby:

class Shape
  def initialize
    @fill_color = nil
  end
 
  def fill_color
    @fill_color
  end
 
  def fill_color=(color)
    raise "Color cannot be red" if color == Color::RED
 
    @fill_color = color
  end
end
This obvious difference being that the Scala example will be type-checked by the compiler, while the Ruby code will not.  This is one of the many areas where Scala demonstrates all the flexibility of Ruby’s syntax coupled with the power and security of Java.

Abstract Methods

One of the important features of the Shape class in the example is that it’s declared to be abstract.  Abstract classes are very important in object oriented design, and Scala wouldn’t be much of an object oriented language if it didn’t support them.  However, looking through the definition of the class, there do not seem to be any abstract methods declared.  Of course, as in Java this is perfectly legal (declaring an abstract class without abstract members), it just doesn’t seem all that useful.
Actually, there are two abstract methods in the Shape class.  You’ll notice that neither the draw nor the area methods are actually defined (there is no method body).  Scala detects this and implicitly makes the method abstract.  This is very similar to the C++ syntax for declaring abstract methods:

class Shape {
public:
    virtual void draw(Graphics *g2) = 0;
    virtual double area() const = 0;
 
    Color *fillColor;
};
Thankfully, this is the end of Scala’s similarity to C++ in the area of abstract types.  In C++, if a class inherits from an abstract base class and fails to implement all of the inherited abstract methods, the derived class implicitly becomes abstract.  If such a situation occurs in Scala, a compiler error will be raised informing the developer (as in Java).  The only exception to this rule are case classes, which are weird enough to begin with and will require further explanation down the road.

Constructors

Despite the best efforts of Josh Bloch, the constructor lives on in the modern object-oriented architecture.  I personally can’t imagine writing a non-trivial class which lacked this virtually essential element.  Now, it may not have been immediately obvious, but all of the Scala classes shown in this post have a constructor.  In fact, every class (and object) has at least one constructor.  Not just a compiler-generated default mind you, but an actually declared in-your-code constructor.  Scala constructors are a bit different than those in Java, which are really just special methods named after the enclosing class:

public class Person {
    public Person(int age) {
        if (age > 21) {
            System.out.println("Over drinking age in the US");
        } 
    }
 
    public void dance() { ... }
}
 
Person p = new Person(26);   // prints notice that person is overage
In Scala, things are done a bit differently.  The constructor isn’t a special method syntactically, it is the body of the class itself.  The above sample is equivalent to the following bit of Scala code:

class Person(age:Int) {
  if (age > 21) {
    println("Over drinking age in the US")
  }
 
  def dance() = { ... }
}
 
var p = new Person(26)   // prints notice that person is over-age
Remember the first Scala example I listed in this series?  (the three line HelloWorld)  In this code, the body of the “main method” is implemented as a constructor in the HelloWorld object.  Thusly:

object HelloWorld extends Application {
  println("Hello, World!")
}
The println statement isn’t contained within a main method of any sort, it’s actually part of the constructor for the HelloWorld object (more on objects in a later post).  Any statement declared at the class level is considered to be part of the default constructor.  The exceptions to this are method declarations, which are part of the class itself.  This is to allow forward-referencing method calls:

class ChiefCallingMethod {
  private var i = 1
 
  if (i < 5) {
    lessFive(i)
  }
 
  def lessFive(value:Int) = println(value + " is less than 5")
}
 
var chief = new ChiefCallingMethod()
This code will run and successfully determine that 1 is indeed less than 5, once again proving the trustworthiness of mathematics.
This constructor syntax seems very strange to those of us accustomed to Java.  If you’re like me, the first thought which comes into your head is: how do I overload constructors?  Well, Scala does allow this, with a few caveats:

class Person(age:Int) {
  if (age > 21) {
    println("Over drinking age in the US")
  }
 
  def this() = {
    this(18)
    println("Created an 18 year old by default")
  }
 
  def dance() = { ... }
}
This revised Person now has two constructors, one which takes an Int and one which takes no parameters at all.  The major caveat here is that all overloaded constructors must delegate to the default constructor (the one declared as part of the class name).  Thus it is not possible to overload a constructor to perform entirely different operations than the default constructor.  This makes sense from a design standpoint (when was the last time you declared such constructors anyway?) but it’s still a little constraining.

Constructor Properties

So you understand Scala constructors and you’re getting the feel for public instance properties, now it’s time to merge the two concepts in constructor properties.  What are constructor properties?  The answer has to do with a (seemingly) odd bit of Scala syntax trivia, which says that all constructor parameters become private instance vals (constants).  Thus you can access constructor parameter values from within methods:

class Person(age:Int) {
  def isOverAge = age > 21
}
This code compiles and runs exactly as expected.  It’s important to remember that age isn’t really a variable (it’s a value) and so it cannot be reassigned anywhere in the class.  However, it might make sense to change a person’s age.  After all, people do (unfortunately) grow older.  Supporting this is surprisingly easy:

class Person(var age:Int) {     // notice the "var" modifier
  def isOverAge = age > 21
 
  def grow() = {
    age += 1
  }
}
In this code, age is no longer just a private value, it is now a public variable (just like fillColor in Shape).  You can see how this can be an extremely powerful bit of syntax when dealing with simple bean classes:

class Complex(var a:Int, var b:Int)
 
// ...
val number = new Complex(1, 0)
number.b = 12
Omission of the curly braces is valid syntax in Scala for classes which do not require a body.  This is similar to how Java allows the omission of braces for single line if statements and so on.  The roughly equivalent Java code would be as follows:

public class Complex {
    private int a, b;
 
    public Complex(int a, int b) {
        this.a = a;
        this.b = b;
    }
 
    public int getA() {
        return a;
    }
 
    public void setA(int a) {
        this.a = a;
    }
 
    public int getB() {
        return b;
    }
 
    public void setB(int b) {
        this.b = b;
    }
}
 
// ...
final Complex number = new Complex(1, 0);
number.setB(12);
Much more verbose, much less intuitive, and far less maintainable.  With the Scala example, adding another property is as simple as adding a parameter to the constructor.  In Java, we have to add a private field, add the getter, the setter and then finally add the extra parameter to the constructor with the corresponding code to intialize the field value.  Starting to see how much code this could save you?
In our code sample way up at the top of the page, Circle declares a property, radius (which is a variable, and so subject to change by code which uses the class).  Likewise Square has a property, width.  These are constructor properties, and they’re about the most cruft-saving device in the entire Scala language.  It’s really amazing just how useful these things are.

Conclusion

We’ve really just scratched the surface of all that Scala is able to accomplish in the object-oriented arena.  The power of its constructs and the elegance of its terse syntax allows for far greater productivity, especially when dealing with a larger project.  Moreover, Scala’s object oriented capabilities prove that it’s not just an interesting functional language for pasty academics but a powerful, expressive and practical language well suited to almost any real-world application.

(codecommit)
read more...

Scala for Java Refugees Part 1: main(String[])

You know who you are.  You’re the developer who picked up Java years ago, maybe as a second language and better alternative to C++, maybe as your first language coming into the industry.  You’re comfortable with Java, you know its ins and outs, its moods.  It’s like an old girlfriend; you may not feel the vibe anymore, but you know just how to rub it so it smiles.  In short, you’re a craftsman, and Java is your workhorse tool.
You’re starting to to become a bit pragmatic about your language choice though.  To put it mildly, the Java honeymoon is over.  While you can hardly find enough fault with the language to just walk away, you’re certainly open-minded enough to consider alternatives.  You’ve heard of this new-fangled thing called Ruby – how could you not have heard, given the sheer noise level produced by its followers.  You’re impressed by the succinctness of its constructs and the power of its syntax, but you’re not sold on the idea of using a scripting language to build your enterprise app.  Dynamic typing and TextMate are all well and good, but for the real-world iron horse you’re going to need something with a bit more backbone.  As a good pragmatist, you stick with the tool that works: Java.
The good news is that there’s light at the end of the tunnel.  There’s a new language on the scene that’s taking the developer world by storm.  Scala seems to offer everything you’ve been looking for in a language: static typing, compiled to bytecode (so you can run it on all those ancient Java-capable servers), a succinct and expressive syntax.  You’ve seen a few examples which have really caught your eye.  It looks the spitting image of Java, except with half the useless constructs thrown out.  No semi-colons, no public static void method qualifiers; it even seems to have some sort of static type inference mechanism.
The only problem you have now is figuring out where to start.  You’ve tried looking on the Scala website, but what you found stopped you in your tracks.  Everything’s so…functional.  Lamdas, high-order functions, immutable state, recursion out the wazoo.  Suddenly things are looking less promising.
Have no fear, ye refugee of Java EE grid iron, all is not lost.  True, Scala is a functional language, but it’s also imperative and highly object oriented.  What does this mean?  It means that you don’t have to write code with the sole purpose of pleasing Haskell Curry.  You can write code that you can actually read a week from now.  You may even be able to show this code to your Java-loving coworkers and they just might understand it.  You don’t have to curry every function and avoid loops at all costs.  You can write your Java applications in Scala.  You just need the right introduction.

Introductions

If you’re like me and can identify with the above, then this series is for you.  I’ve read a lot of articles and tutorials on Scala (Alex Blewitt’s series is highly recommended, especially if you’re interested in the more functional side of life), but few of these tutorials have even attempted to make things easier for the run-of-the-mill Java developer to make the transition.  I personally have very little FP (Functional Programming) experience, so I don’t think I could write an article about porting Scheme code to Scala even if I wanted to.  Instead, this series will focus on how Scala is just like Java, except better.
Did I mention Alex’s Scala introduction series?  Seriously, this is great reading, and not a bad introduction to Scala in and of itself.  Once you’re done reading my ramblings, you should run over and read some of his more coherent stuff.   The more the merrier!

Getting Started


object HelloWorld extends Application {
  println("Hello, World!")
}
Nothing like getting things rolling with a little code.  Notice the refreshing lack of mandatory semicolons.  We can use them anyway, but they aren’t required unless we need multiple statements on a single line.  This code sample does exactly what it looks like, it defines an application which (when run using the scala interpreter) will print “Hello, World!” to stdout.  If you put this code into a file with a .scala extension, you can then compile it using the scalac compiler.  The result will be a single .class file.  You could technically run the .class using the java interpreter, but you would have to mess with the classpath a bit.  The easiest thing to do is just use the scala command like so:

scalac hello.scala
scala HelloWorld
Notice the name of the file in question?  Unlike Java, Scala doesn’t force you to define all public classes individually in files of the same name.  Scala actually lets you define as many classes as you want per file (think C++ or Ruby).  It’s still good practice to follow the Java naming convention though, so being good programmers we’ll save our HelloWorld example in a file called “HelloWorld.scala”.

Editors

Just a brief note on your first few moments with Scala: using the right editor is key.  As you must have learned from your many years in the Java world, IDEs are your friend.  Scala, being a much younger language doesn’t have very good IDE support yet.  It is a static, general purpose language like Java, so IDE support will be forthcoming.  For the moment however, you’re stuck with a very limited set of options.
  • Eclipse (using one of two shoddy and unstable Scala plugins)
  • Emacs
  • IntelliJ (basically just syntax highlighting support)
  • TextMate
  • VIM
  • jEdit
There are a few other options available, but these are the biggies (to see a full list, look in the misc/scala-tool-support/ directory under the Scala installation root).  My personal recommendation is that you use jEdit or TextMate, though if you’re feeling adventurous you’re free to try one of the Eclipse plugins too.  Scala support in Eclipse has the advantage (at least with the beta plugin) of features like semantic highlighting, code completion (of both Scala and imported Java classes) and other IDE-like features.  In my experience though, both Eclipse plugins were unstable to the point of unusable and as such, not worth the trouble.  Scala is a much cleaner language than Java, so it really does have less of a need for a super powerful IDE.  It would be nice, no question about that, but not essential.

More Hello World


object HelloWorld2 {
  def main(args:Array[String]) = {
    var greeting = ""
    for (i <- 0 until args.length) {
      greeting += (args(i) + " ")
    }
    if (args.length > 0) greeting = greeting.substring(0, greeting.length - 1)
 
    println(greeting)
  }
}
Save this in a new file (we’ll call it “HelloWorld2.scala”), compile and run using the following commands:

scalac HelloWorld2.scala
scala HelloWorld2 Hello, World!
Once again, this prints “Hello, World!” to stdout.  This time we did things a little differently though.  Now we’ve got command line arguments coming into our app.  We define a variable of type String, iterate over an array and then call a bit of string manipulation.  Fairly straightforward, but definitely more complex than the first example.  (Note: Scala mavens will no doubt suggest the use of Array#deepMkString(String) (similar to Ruby’s Array::join method) instead of iterating over the array.  This is the correct approach, but I wanted to illustrate a bit more of the language than just an obscure API feature).
The first thing to notice about this example is that we actually define a main method.  In the first example, we just extended Application and declared everything in the default constructor.  This is nice and succinct, but it has two problems.  First, we can’t parse command line args that way.  Second, such examples are extremely confusing to Scala newbies since it looks more than slightly magical.  Don’t worry, I’ll explain the magic behind our first example in time, but for now just take it on faith.
In the example, we define a main method that looks something like our old Java friend, public static void main.  In fact, this is almost exactly the Scala analog of just that method signature in Java.  With this in mind, an experienced developer will be able to pick out a few things about the language just by inspection.
First off, it looks like all methods are implicitly public.  This is somewhat correct.  Scala methods are public by default, which means there’s no public method modifier (private and protected are both defined).  It also looks like Scala methods are static by default.  This however, is not entirely correct.
Scala doesn’t really have statics.  The sooner you recognize that, the easier the language will be for you.  Instead, it has a special syntax which allows you to easily define and use singleton classes (that’s what object means).  What we’ve really declared is a singleton class with an instance method, main.  I’ll cover this in more detail later, but for now just think of object as a class with only static members.
Upon deeper inspection of our sample, we gain a bit of insight into both Scala array syntax, as well as an idea of how one can explicitly specify variable types.  Specifically, let’s focus on the method declaration line.

def main(args:Array[String]) = {
In this case, args is a method parameter of type Array[String].  That is to say, args is a string array.  In Scala, Array is actually a class (a real class, not like Java arrays) that takes a type parameter defining the type of its elements.  The equivalent Java syntax (assuming Java had an Array class) would be something like this:

public static void main(Array<String> args) {
In Scala, variable type is specified using the variable:Type syntax.  Thus, if I wanted to declare a variable that was explicitly of type Int, it would be done like this:

var myInteger:Int
If you look at the sample, we actually do declare a variable of type String.  However, we don’t explicitly specify any type.  This is because we’re taking advantage of Scala’s type inference mechanism.  These two statements are semanticly equivalent:


var greeting = ""


var greeting:String = ""
In the first declaration, it’s obvious to us that greeting is a String, thus the compiler is able to infer it for us.  Both greetings are staticly type checked, the second one is just 7 characters shorter.  :-)
Observant coders will also notice that we haven’t declared a return type for our main method.  That’s because Scala can infer this for us as well.  If we really did want to say something explicitly, we could declare things like this:

def main(args:Array[String]):Unit = {
Once again, the type antecedes the element, delimited by a colon.  As an aside, Unit is the Scala type for I-really-don’t-care-what-I-return situations.  Think of it like Java’s Object and void types rolled into one.

Iterating Over an Array


var greeting = ""
for (i <- 0 until args.length) {
  greeting += (args(i) + " ")
}
By the way, it’s worth noting at this juncture that the convention for Scala indentation is in fact two spaces, rather than the tabs or the four space convention that’s so common in Java.  Indentation isn’t significant, so you can really do things however you want, but the other four billion, nine hundred, ninety-nine million, nine hundred, ninety-nine thousand, nine hundred and ninety-nine people in the world use the two space convention, so it’s probably worth getting used to it.  The logic behind the convention is that deeply nested structure isn’t a bad sign in Scala like it is in Java, thus the indentation can be more subtle.
This sample of code is a bit less intuitively obvious than the ones we’ve previously examined.  We start out by declaring a variable, greeting of inferred type String.  No hardship there.  The second line is using the rarely-seen Scala for loop, a little more type inference, method invocation on a “primitive” literal and a Range instance.  Developers with Ruby experience will probably recognize this equivalent syntax:

for i in 0..(args.size - 1)
  greeting += args[i] + " "
end
The crux of the Scala for loop is the Range instance created in the RichInt#until method.  We can break this syntax into separate statements like so:

val range = 0.until(args.length)
for (i <- range) {
Oh, that’s not a typo there declaring range using val instead of var.  Using val, we’re declaring a variable range as a constant (in the Java sense, not like C/C++ const).  Think of it like a shorter form of Java’s final modifier.
Scala makes it possible to invoke methods using several different syntaxes.  In this case, we’re seeing the value methodName param syntax, which is literally equivalent to the value.methodName(param) syntax.  Another important action which is taking place here is the implicit conversion of an Int literal (0) to an instance of scala.runtime.RichInt.  How this takes place isn’t important right now, only that RichInt is actually the class declaring the until method, which returns an instance of Range.
Once we have our Range instance (regardless of how it is created), we pass the value into the magic for syntax.  In the for loop declaration, we’re defining a new variable i of inferred type Int.  This variable contains the current value as we walk through the range [0, args.length) - including the lower bound but not the upper.
In short, the for loop given is almost, but not quite equivalent to the following bit of Java:

for (int i = 0; i < args.length; i++) {
Obviously the Java syntax is explicitly defining the range tests, rather than using some sort of Range object, but the point remains.  Fortunately, you almost never have to use this loop syntax in Scala, as we'll see in a bit.
The body of the loop is the one final bit of interesting code in our sample.  Obviously we're appending a value to our greeting String.  What I'm sure struck you funny (I know it did me) is the fact that Scala array access is done with parentheses, not square brackets.  I suppose this makes some sense since Scala type parameters are specified using square brackets (rather than greater-than/less-than symbols), but it still looks a little odd.
To summarize, the upper sample in Scala is logically equivalent to the lower sample in Java:


var greeting = ""
for (i <- 0 until args.length) {
  greeting += (args(i) + " ")
}


String greeting = "";
for (int i = 0; i < args.length; i++) {
    greeting += args[i] + " ";
}

A Better Way to Iterate

In Java 5, we saw the introduction of the so-called for/each iterator syntax.  Thus, in Java we can do something like this:

for (String arg : args) {
    greeting += arg + " ";
}
Much more concise.  Scala has a similar syntax defined as a high-order function - a function which takes another function as a parameter.  I'll touch on these more later, but for the moment you can take it as more magic fairie dust:

args.foreach { arg =>
  greeting += (arg + " ")
}
Here we see that foreach is a method of class Array that takes a closure (anonymous function) as a parameter.  The foreach method then calls that closure once for each element, passing the element as a parameter to the closure (arg).  The arg parameter has an inferred type of String because we're iterating over an array of strings.
Now as we saw earlier, Scala methods can be called in different ways.  In this case we're calling foreach omitting the parentheses for clarity.  We also could have written the sample like this:

args.foreach(arg => {
  greeting += (arg + " ")
})
Scala actually defines an even more concise way to define single-line closures.  We can omit the curly-braces altogether by moving the instruction into the method invocation:

args.foreach(arg => greeting += (arg + " "))
Not bad!  So our fully rewritten sample looks like this:

object HelloWorld2 {
  def main(args:Array[String]) = {
    var greeting = ""
    args.foreach(arg => greeting += (arg + " "))
    if (args.length > 0) greeting = greeting.substring(0, greeting.length - 1)
 
    println(greeting)
  }
}
The syntax looks great, but what is it actually doing?  I don't know about you, but I hate having to use APIs that I don't know how to replicate myself.  With a bit of work, we can recreate the gist of the Scala foreach method in pure Java.  Let's assume for a moment that Java had an Array class.  In that Array class, let's pretend there was a foreach method which took a single instance as a parameter.  Defined in code, it might look like this:

public interface Callback<T> {
    public void operate(T element);
}
 
public class Array<T> {
    // ...
    public void foreach(Callback<T> callback) {
        for (T e : contents) {   // our data structure is called "contents"
            callback.operate(e);
        }
    }
}
I could have defined foreach recursively (as it is defined in Scala), but remember I'm trying to keep these explanations clear of the tangled morass that is FP.  :-)
Sticking with our goal to see an analog to the Scala foreach, here's how we would use the above API in Java:

public class HelloWorld2 {
    public static void main(Array<String> args) {
        final StringBuilder greeting = new StringBuilder();
        args.foreach(new Callback<String>() {
            public void operate(String element) {
                greeting.append(element).append(' ');
            }
        });
        if (args.length() > 0) {
            greeting.setLength(greeting.length() - 1);
        }
 
        System.out.println(greeting.toString());
    }
}
Starting to see why Scala is legitimately appealing?  If you're like me, you just want Scala to be a more concise Java.  In this case, that's exactly what we've got.  No strange functional cruft, no immutable state.  Just solid, hard-working code.

A Word About Built-in Types

Because Scala is built on the JVM, it inherits a lot of its core API directly from Java.  This means you can interact with Java APIs.  More than that, it means that any code you write in Scala is using Java APIs and functions.  For example, our sample HelloWorld2 is using a string variable greeting.  This variable is literally of type java.lang.String.  When you declare an integer variable (type Int) the compiler converts this to the Java primitive type int.
It's also worth noting that there are a number of built-in implicit conversions (just like the Int to RichInt we saw earlier with the Range creation).  For example, Scala's Array[String] will be implicitly converted to a Java String[] when passed to a method which accepts such values.  Even Scala type parameters are available and interoperable with Java generics (in the current development version of Scala and slated for inclusion in 2.6.2).  In short, when you use Scala you’re really using Java, just with a different syntax.

Conclusion

Scala doesn’t have to be complex, needlessly academic or require a master’s degree in CompSci.  Scala can be the language for the common man, the 9-5 developer who’s working on that next enterprise web application.  It has real potential to provide the clear syntax Java never had without forsaking the power and stability of a trusted, first-class language.  Convinced?
Up next, classes, methods and properties: everything you need to know to get rolling with object-oriented programming in Scala.


(codecommit)
read more...