Monday, May 12, 2008

Get smart with properties in Scala

Properties are easy to declare in Scala

class ShoePhone
{
    var vibrateOn = false
    var volume = 8
}


What does this really mean?

Here is the same code, written in a more cluttered way, illustrating the setters and getters which are automatically generated above
class ShoePhone
{
    private[this] var _vibrateOn: Boolean = false;
    private[this] var _volume: Int = 8;

    def vibrateOn: Boolean = _vibrateOn;
    def volume: Int = _volume;

    def vibrateOn_=(on: Boolean)
    {
        _vibrateOn = on;
    }

    def volume_=(vol: Int)
    {
        _volume = vol;
    }
}
Here the private fields are given names with an added underscore prefix. These names could be anything. This is just a convention I'd like to see. I don't like seeing a lot of one-off names (such as the ones I used for the setter method parameters, on and vol). If there is a simple way to eliminate the one-off names akin to what one finds in the Java idiom
this.volume=volume;
please let me know.

The getter methods are defined without parentheses so they appear in code just as if they were fields. See previous post on the Uniform Access principle.

The setter methods are defined by adding
_=
This suffix creates the method used when a variable is assigned using
=
Say we have a ShoePhone instance shoePhone and set its volume
shoePhone.volume = 0
You could write to the same effect
shoePhone.volume_=(0)

For an explanation of the access modifier private[this] see The Scala cone of silence.



----------------
Now playing: Yeasayer - 2080
via FoxyTunes

Version 1.1 (correction)

Update (May 22, 2008): Using the Java Class File disassembler javap on the ShoePhone class file, you can see what Scala does behind the scenes in the Java bytecode
javap -private ShoePhone

Compiled from "ShoePhone.scala"
public class com.control.equipment.ShoePhone extends java.lang.Object implements scala.ScalaObject{
    private int volume;
    private boolean vibrateOn;
    public com.control.equipment.ShoePhone();
    public void volume_$eq(int);
    public int volume();
    public void vibrateOn_$eq(boolean);
    public boolean vibrateOn();
    public int $tag();
There are private fields and public getter methods which use the same name. The setter method adds the suffix  _=  cryptically rewritten as  _$eq  to comply with Java naming rules.

If your setter method needs to do something special, you can always define it explicitly
class ShoePhone
{
    var _vibrateOn = false

    private[this] var _volume = 8

    def volume = _volume

    def volume_=(__volume: Int)
    {
        assert(__volume>=0)
        assert(__volume<=8)
        _volume = __volume;
    }
}
where I've used an underscore prefix to distinguish the private variable from the public getter method, again to avoid one-off names. I've used two underscores for the explicit setter method parameter. The use of underscores at the beginning of names is discouraged in Java. If anyone knows a better, less discouraged, more aesthetic way to do this, please let me know.

Update (May 23, 2008): If you need your ShoePhone available as a JavaBean, it's easy. Just use the annotation @scala.reflect.BeanProperty.
class ShoePhone
{
    @scala.reflect.BeanProperty
    var vibrateOn = false

    @scala.reflect.BeanProperty
    var volume = 8
}
The setters and getters will then be generated automatically for you by the Scala compiler.
javap ShoePhone

Compiled from "ShoePhone.scala"
public class com.control.equipment.ShoePhone extends java.lang.Object implements scala.ScalaObject{
    public com.control.equipment.ShoePhone();
    public void setVolume(int);
    public int getVolume();
    public void setVibrateOn(boolean);
    public boolean isVibrateOn();
    public void volume_$eq(int);
    public int volume();
    public void vibrateOn_$eq(boolean);
    public boolean vibrateOn();
    public int $tag();

Friday, May 09, 2008

The Scala cone of silence

I've been waiting so long for this. Now with Scala you can restrict access to your classes by package name, allowing only a package and its nested packages access. Say you had the packages,

com.control
com.control.agent
com.control.agent.special
Then the access modifier private[agent] would limit access to the last two packages only.

You can also define members as object-private with the access modifier private[this]. This restricts access to the specific instance. In Java, other instances of the same class can access private fields. Did you realize that?

What a wonderful cone of silence!

Wednesday, April 02, 2008

Gaga over Scala

Scala, scala, scala....

I'll try to comment more once I collect myself, if I ever do.

Scala blends functional and object-oriented programming into one language, which runs on a JVM, interoperably with Java. Why functional programming (FP)? What's functional programming? Here's an interesting summary - Functional Programming for the Rest of Us.

Update (Apr 9, 2008, 10:40 am Central):
Here's an excellent audio overview by one of the authors of the book Programming in Scala (whom I had the privilege of mountain biking with in August 2001 at Crested Butte, Colorado, while attending a week-long seminar on Design Patterns he and Bruce Eckel taught) This introduction, which I just listened to, includes most all the key points I mentioned to a friend of mine in an enthusiastic conversation yesterday evening. Venners captures much of the unrest in the Java community that I have sensed over the past several years. He captures well my own hesitation to jump into Ruby, Python, and Groovy as solutions to this angst and my immediate determination that Scala is it, the language we've been waiting for - Bill Venners on the rise of Scala

Update (Apr 28, 2008, 2:10 pm Central): I've read Programming in Scala cover-to-cover, and I'm still gaga.

My guess is that Scala is "it", the language that will supercede Java, more speedily if it markets itself like Spring, by putting forward the Actor library as the entry point and not forcing people to adopt everything all at once, given its interoperability with Java.

X10 is also interesting. Might Scala adopt x10's notion of a clock? Perhaps there'll be some sort of interoperability between X10 and Scala, or even a hybrid. I imagine Lex Spoon has some things to say on this matter, having been involved with both projects. Indeed, I see from Spoon's CV that he "assisted with the ongoing design of X10, a language for high-performance computing, both in its pure form and with a Scala-like front-end."

I have questions about Scala's classloading and security. Do they differ from Java's?

Update (May 9, 2008, 1:50 pm Central): Odersky, Spoon, and Venners published a new version of their Pre-Print edition this last Sunday, May 4. And what do you know? They added a new section on clocks in chapter 30 "Actors and Concurrency". I'd like to think one of the comments I had submitted to them online sparked this addition, but I don't know. I read it yesterday. It's great.

Update (May 9, 2008, 5:52 pm Central): Here's one small example of some code in Scala that speaks to its power. It's based on an example from the book.

val name = "Agent 99"
val nameHasDigit = name.exists(_.isDigit)

Here the String type is implicit in the first line, but it could be spelled out explicitly, along with a semi-colon at the end of the line
val name: String = "Agent 99";

In the second line, the method exists applies a boolean function to a sequence of objects, returning true if at least one of the results is true. Since name is a string not a sequence, it's implicitly converted to a sequence of characters. The function is described by a function literal, but it could have been defined using the symbol f with some code like this
def f(ch: Char): Boolean = ch.isDigit();
val nameHasDigit: Boolean = name.exists(f);
or alternatively
def f(ch: Char) = ch.isDigit
val nameHasDigit = name.exists(f)
Notice how clean the code becomes, how much more readable it is, when obvious things can be removed.


Details, details, details...

A function literal, by the way, is also known as a predicate when it returns a Boolean, as _.isDigit does above.

One detail. If you already know Scala, can you find the error in my expanded pedagogic code for defining the function f?

In Scala, there is a coding convention for differentiating between commands and queries (see Bertrand Meyer's writing on the Command-Query Separation principle). Queries return information without causing "side-effects". Commands change objects. The convention in Scala is to only include empty parentheses when the method has side-effects. When it returns information without changing things, returning say a conceptual property of an object, then it's a query, and, again in the spirit of Bertrand Meyer's writing, in this case on the Uniform Access principle, the parentheses are removed. That's the Scala convention.

If the code defining the method specifically omits parentheses however, then this isn't optional. It's enforced, as in the case of isDigit. You'll see a compile-time error if you try to call the method with empty parentheses.

I also didn't mention that scala.Char is implicitly converted to scala.runtime.RichChar, behind the scenes. Implicit conversion makes for more intuitive, succinct code. It also allows you to wrap code from pre-existing libraries using traits. Traits are akin to Java interfaces, however they can include concrete implementations, and so they're mixins.

Another detail - the implicit conversion for exists actually requires an Iterable. A sequence is, more precisely, a Seq, a subtrait of Iterable. The conversion is made from String to a RandomAccessSeq, a subtrait of Seq, by one of the implicit conversion functions in a singleton object called Predef, where many such common conversions are defined.

In Scala, by the way, in addition to defining a class, you can define an object, which is just a singleton. You can define a class and an object using the same name, in which case the object is the companion object to the class. So every Scala class can have an associated singleton object.

Update (May 13, 2008, 8:15 pm Central):
I noticed an announcement for the first meeting of a new Scala User Group for the San Francisco Bay Area. It's scheduled to meet at this very moment. Wish I were there. Maybe their next meeting, or the meeting after that....

Here in Minneapolis, I hope to meet other Scala users at the OTUG meeting next week, where Ted Neward is making a presentation - The Busy Developer's Guide to Scala
The Java platform has historically been the province of object-oriented programming, but even Java language stalwarts are starting to pay attention to the latest old-is-new trend in application development: functional programming. In this lecture, Ted Neward introduces Scala, a programming language that combines functional and object-oriented techniques for the JVM. Along the way, Ted makes the case for why you should take the time to learn Scala — concurrency, for one — and shows you how quickly it will pay off.
So far I only know one other programmer in the Twin Cities who's interested in Scala, and I had a coffee klutch with him yesterday evening on the subject. It'd be great to get a Scala User Group going here, starting with some of the attendees of Neward's talk.