Learning Scala: Day Three

If you’ve been following my previous installments into Learning Scala, you might recall that I was ploughing ahead well into chapter 4 of Programming in Scala the last time we met. I’ve made it passed that point, and I’ve already reached into chapter 7. I did get a little bogged down from real life obligations and such, so I’d like to take a break from it and jot down some of my thoughts.

What I’ve covered thus far

It would be something of a lie to say I haven’t read about a lot of things. Some of them I know (classes and objects, Java data types), and many of them I don’t. Up to this point, the book has discussed classes; objects; singleton objects; basic types; more about operators-as-methods; a few blurbs about how Scala handles infix, prefix, and postfix notations; symbols, which is how Scala defines true and false; “functional objects” (I have an example from the text for this bit–more later); differences from Java and how Scala handles constructors; something called “pre-conditions” which are awesome; identifiers, which is a fancy term for referencing things in the Java library that contain reserved words in Scala; and finally, control structures. I still have a few things left in chapter 7 to cover–including exception handling–but I think much of what remains is similar enough to other languages that I can put off a discussion over those topics until day four.

Some minor hitches

I’ve encountered more than a few hitches. They haven’t been bad, but they’ve been enough to stop me briefly until I could figure out what I was doing wrong. So far, there is one particularly bad stumbling block that has caught me off guard more than once. I should have known better because I’ve read about it in at least four chapters. Yet, I’m still running headlong into the issue. I think I can avoid it in the future by writing it out; at the very least, this will help me remember. Here’s what it is:

1
2
3
4
5
class Example {
    def doSomething (a: String): String = {
        a += "something"
    }
}

Looks good, doesn’t it? Not so fast. Compiling this generates an error “reassignment to val“. Ooops! That’s right, function arguments are vals, and vals cannot be reassigned to once they are created. At this point, I knew that the last expression that yields a value qualifies as a return statement (you don’t need explicit returns in Scala), but evidently, I had neglected the small fact that a += "something" is an attempt to concatenate a string with the contents of a and inject the resulting string back into the val. Big mistake. What I meant to write should have turned out like this:

1
2
3
4
5
class Example {
    def doSomething (a: String): String = {
        a + "something"
    }
}

By writing a + "something" instead, no reassignment is occurring with a. Rather, a is being concatenated with the string "something" and since it’s the last expression in the function, the resulting value is returned. doSomething now performs as expected:

scala> var c = new Example()
c: Example = Example@1629e96

scala> c doSomething "what should I do? "
res0: String = what should I do? something

The other problems I’ve run into are largely related to the change in IDEs I had to make (more later–sorry to keep you waiting!). I’ve been doing the usual stupid beginner mistakes of adding parenthesis where they shouldn’t be (mostly by accident) and omitting them where they ought to be (another accident). I’m not exactly certain why I do this; I suspect it has something to do with the minor rewiring of adjusting to a new syntax. But, I’d rather attribute it to the change in IDEs. This is the same thing that plagued me for about a week or so when I was first learning C#. I expect these minor bumps will be gone by next Monday.

More on methods

I know I talked a little bit about methods-as-operators last time. It’s really cool, and you’ve gotten to see another example (above) in the doSomething method. Since Scala treats methods that return a value and accept exactly one value themselves as an operator, you could therefore write our little class Example call above as either c.doSomething("what should I do? ") or, as I wrote instead, c doSomething "what should I do? ". With Scala’s handling of single-argument methods as operators, it is possible to override all of the basic operators +, -, /, and *. You can even make your own, if you like. The only exception is with the dollar sign ($). Scala uses dollar signs to mangle calls before passing them on to the JVM, so introducing the symbols into your own code will probably cause problems.

However…

Overriding the basic arithmetic operators is all well and good. However, if you try to do the same thing with the arguments swapped, you’ll wind up with an error. Here’s our Example class again:

scala> "what should I do? " doSomething c
:7: error: value doSomething is not a member of java.lang.String
       "what should I do? " doSomething c

Uh oh!

Well, maybe not. doSomething is defined only in our Example class. Since String has no idea what doSomething means, the compiler complains and spits out this particular error. There is a solution using implicit def to create an implicit function call within the current scope that resolves this issue. If we were to refactor our Example class’ doSomething method (or simply write an override for it), we could add this into the interpreter and it’d work exactly as expected:

implicit def stringToExample (s: String) = new Example(s)

I haven’t yet completed a version of the class that does this correctly. I do have a version that will compile but the results are unexpected.

A change of pace…

I mentioned at least once (or was that twice?) that I had to change my IDE. I haven’t explained why, so if you’re curious, let me do that here. First, there’s something important you should know.

The Eclipse Scala plugin does not work

I take that back. It worked exactly once. Then I waited about a week, updated Eclipse, and now it’s broken. 2.7.5 doesn’t work, the nightly builds of 2.8.0 don’t work, and neither does the version I downloaded some time back. Whatever happened broke it. I even downloaded Eclipse via Pulse (which is pretty nice, BTW–I’ll link to it in this week’s LotW), tried the plugin that came with it (which was dated), and that didn’t work.

So, in case you missed it: The Eclipse Scala plugin does not work. They’re working on it, and I’m sure the Scala folks will have a working version up again within a couple of weeks. I take that back: It works. It’s just that it reads Scala sources as Java, even with JDT weaving enabled. I played with it for at least four hours over this weekend, but I’m not going to waste any more time until I have something I can just drop in, click a couple buttons, and have working. I’m not familiar with Eclipse’s internals nor is it something I’m particularly interested at this time (that may change), so I’d much rather have an IDE that just works with Scala.

Netbeans, on the other hand, has a working plugin for Scala. Some things are a little flaky but syntax highlighting works as do some mouse-over/error messages. Javadoc-style comment completion, multiline completion, and proper tabbing of braces when closing methods and classes don’t work. Thankfully, those are simply incidentals that can be dealt with.

It’s just a shame I’ve grown so spoiled with typing /** [ENTER] and having the enter comment block written for me… Oh well.

Just remember: If you’re learning Scala sometime during the latter half of 2009, you might want to save yourself the trouble and download Netbeans if you don’t already use it. Eclipse is my favorite IDE but it just doesn’t work. (Don’t get me ranting on their plugin infrastructure…)

A word about objects

Scala, unlike Java, PHP, C++, C#, and a few other OOP-style languages doesn’t have exactly the same notion of static methods. In Java, where you might write something like:

public class Calculator
{
    public static int doCalculation (int x, int y)
    {
        return x + y;
    }
}

And then call this method with: Calculator.doCalculation(4,2). Don’t try doing the same thing with Scala. In other words…

class Calculator {
    def doCalculation (x: Int, y: Int) = { x + y }
}
 
// Call this from the interpreter and you'll receive:
scala> Calculator.doCalculation(4,2)
<console>:7: error: value doCalculation is not a member of object Calculator
       Calculator.doCalculation(4,2)

Instead, you have to use something called singleton objects. If I’m remember the text correctly, singleton objects are instantiated (created) the first time they’re called. They’re also named after the class whose static-like methods they implement. For example, if we instead wrote our class (above) like this, splitting it apart into a class and a singleton object:

class Calculator {
}
object Calculator {
    def doCalculation (x: Int, y: Int) = { x + y }
}

And we run the interpreter:

scala> Calculator.doCalculation(4,2)
res8: Int = 6

…we’d receive exactly what we expected.

Now, I’m going to come right out and say this. I’ll probably be labeled a Scala fanboy, too, and that’s fine by me. I actually like this design requirement. Static methods can clutter a class quickly. This is especially true for classes that contain both static and non-static members. If you’ve dealt with thousand-line classes that have a mix of factory methods (static of course) and non-static methods that do useful work within the context of the class, you know what I mean. I imagine that factory methods work in Scala as they do in other languages, but I what I can’t imagine is the well-needed relief this will bring to the world to force static members into a singleton.

To be fair, it’s possible to do something similar to this in C# by using partial classes. In fact, partial classes is one of the things I really love about C#. If you have a class that happens to be especially big, separating it into multiple source files is easy using the partial keyword. The Visual Studio designer makes liberal use of partial classes, so if you’re hard-pressed for an example, you shouldn’t have to look too far.

Constructing constructors

Scala handles constructors a little differently than does Java. First, all constructor overloads must call the parent constructor or another constructor that does. In other words, this will work:

class Calculator (i: Int, j: Int) {
    val x = i
    val y = j
    def this (i: Int) = { this(i, 0) }
    def this () = { this(0,0) }
}

This won’t:

class Calculator (i: Int, j: Int) {
    val x = i
    val y = j
    def this () = { this() }
}

However, using the first example, calling Calculator without any arguments results in an implicit assignment (since we created an empty constructor by passing 0 to all of our arguments):

scala> val c = new Calculator()
c: Calculator = Calculator@12a7c1e

scala> c.x
res11: Int = 0

I’m not so sure I can quite see what the best practice is for this particular facet of classes, but I expect it will come clear in the later chapters. Chapters 21-28 have been repeatedly referenced during the course of my reading, and I should think that they’ll clarify some of the things that are on my mind. Specifically, I’m curious about:

  • What is the best practice, then, for creating classes with multiple constructors?
  • What about classes that might have to deal with different data types, such as Int and Float?
  • Initialization is necessary, isn’t it? How are we supposed to use classes if we’re encouraged to use vals where possible but cannot reassign to them? Is this one of the cases where using a var is appropriate?

Pre-conditions kick some serious posterior

Here’s something that Java developers would kill for: Have you ever wanted a way to write–with one line of code–an insurance policy to verify that the arguments passed into your constructor are valid? In Scala, you can. Take this for example:

class Precondition (x: Int) {
    require(x > 0)
    val number = x
}

Now, load this class up in the interpreter and try the following. Watch carefully and see what happens if I pass in a value where x is less than or equal to 0:

scala> val c = new Precondition(1)
c: Precondition = Precondition@1e04a35

scala> val c = new Precondition(0)
java.lang.IllegalArgumentException: requirement failed
        at scala.Predef$.require(Predef.scala:107)
        at Precondition.(:7)
        at .(:7)
        at .()
        at RequestResult$.(:3)
        at RequestResult$.()
        at RequestResult$result()
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeM...

That’s pretty nice, isn’t it? One line of code can verify that the constructor has been treated correctly by client code. Yes, this is possible in Java using “only one line” of code–or is it? Let’s have a look… I’ll even include line numbers just to be a jerk.

1
2
3
4
5
6
7
8
9
10
11
public class Precondition
{
    private int x;
    public void Precondition (int x)
    {
        if (x > 0)
            this.x = x;
        else
            throw Exception();
    }
}

Hmm, that’s four lines of code to do roughly the same thing. It’s also bad practice to have all that in the constructor. Let’s do this the Right Way.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Precondition
{
    private int x;
    public void Precondition (int x)
    {
        this.setX(x);
    }
 
    public void setX (int x)
    {
        if (x > 0)
            this.x = x;
        else
            throw Exception();
    }
}

There, one line of code! Can’t you see it? You can’t?! I’m talking about the constructor, only. No, really! Oh, that mutator method? Yeah… I had to add that to game the rules of this particular challenge. Fine, you want one line of code, do you?

1
2
3
4
5
6
7
8
public class Precondition
{
    private int x;
    public void Precondition (int x)
    {
        if (x > 0) this.x = x; else throw Exception();
    }
}

There. One line. Unreadable? Yeah, it is. So what.

“So what,” they might say. Frankly, I prefer readability over the ability to write fewer lines of code especially when those lines of code are compressed. You simply can’t beat the require statement.

Conclusion

I’ve covered a lot of ground here. At least, it seems like a lot. All told, these chapters took about 4 hours of off-and-on reading for me to complete. That includes time for interruptions and breaks. Scala isn’t hard. It is a paradigm shift, and I’m still not sure how well I’m following along with the functional part of the language. I suppose we’ll see how well I do in the coming weeks as I add further installments into my journal: Learning Scala.

See you next time. Oh, and I promise I’ll have a LotW up tomorrow. Don’t expect it ’til the evening, but I think you should have plenty to read until then.

Cheerio and all that rot.

No comments.
***

Learning Scala: Day Two

Today marked my progress through chapters 2, 3, and a small part of 4 (more on that next time; it’s about stuff I largely already know but adds some of Scala’s own twist to classes and the likes). So far, the biggest hurdle is the syntax. It’s like a strange mix between Java, Python, and even a little BASIC (because of the array indices). I can certainly feel the influences other languages have had on Scala already!

The unusual thing is that I’m starting to catch on to the more fundamental principle behind functional languages: Functions should have no side effects. Really, it makes far more sense. When performing a replace operation on a string, for example, the original object should not be modified; instead, a new object is returned with the replacements applied and the original object remains untouched.

It is no surprise then that Scala includes data structures that fall into two categories: mutable and immutable. Near as I can gather at this point, the former is intended for imperative-style writing while the latter is preferred for functional. But, that’s simply where the fascinating bits start. Let’s take a look at tuples.

The Tuple

Like Python (and a few other languages), Scala has a tuple construct that provides an array-like immutable data structure that can be used as keys, key/value pairs, and so forth. The biggest difference, as I can tell, is that Scala tuples aren’t exactly like Python tuples; you can’t use array-like indices to reference a tuple offset. Instead, it appears that you really need to know the structure of the tuple ahead of time. Mind you, that’s not a big deal as Scala provides many other data structures that could be used as a Python tuple might.

You can build things with tuples, but let’s explore objects

I’m really excited about some of the things I’ve learned related to tuples. For the sake of clarity, however, I really need to discuss one of the more interesting things I learned related to objects in Scala. As such, I hope that you’ll forgive me for the brief digression. I have a lot of things to cover, so backtracking is sometimes a necessary evil!

Speaking of backtracking, I suspect this post will work roughly like our memories. To illustrate, think of a time when you were walking along a sidewalk on a beautiful day. Beams of sunlight were streaming between the trees as the shadows of birds scaled their way up the hill before you. The birds almost immediately enter your field of view and then you encounter an incredibly perfume floating about on the air. You turn and notice a handful of flowers sprouting among the bushes to your left, and then you remember a particular chore you still had to take care of–such as delivering flowers to your girlfriend, mother, or what have you.

Then a neighborhood dog barks and instantly shatters the serenity of this landscape into a million pieces. The birds are a distant memory, the fragrance of flowers have been blown away on the brisk morning air, and the only thing in your mind is a vague sense of frustration. That damned dog ruined it all.

Next, some random idiot comes careening passed you on his bicycle–nearly hitting you. You spit in anger briefly as the rush of air blows by. You notice that a magazine in his book back flies out across the sidewalk and blows onto the road. Glancing at the rolled up paper briefly, you wonder if the approaching car is fated to hit it. You smirk wryly, maybe even consider what a joy karma is in moments like these, and then the vehicle swerves away from the magazine. That moron on the bike apparently noticed that his bag had come loose and sent a few of his things flying into the air like a swarm of stirred up bees. He sheepishly walks his bike passed you.

As you glance at the man, you start to think back on what that chore was you so wished you could remember. Birds? Maybe it was chicken. No, wait, we fixed chicken for dinner last night. Hmmm…

And then you think about it for a few minutes more. You even consider for a moment the prospect of retracing your steps from earlier in the morning. Those flowers smelled so wonderful… EUREKA!

Then it hits you.

That’s sort of what the purpose of my backtracking is. It serves to both jog my memory as well as grant me an excuse to make up a story to share.

The world of objects in Scala

Scala, like Python, is what I would call a “pure” object-oriented programming language. Everything is an object. Operations call methods on each object (including integers). However, unlike Python, there are no true operations. +, -, /, and * are all individual methods; in Python, the + operator calls the object’s __add__ method whereas in Scala, there exists a method called, quite literally, +. That’s it. Thus, in Scala, addition can be written in two ways:

// Addition using "standard" syntax:
var added = 1 + 2
 
// Addition using method calls:
var added = (1).+(2)
 
// ...which could also be written as:
var added = 1.+(2)

Isn’t that interesting? What’s more, every single operator in Scala is a method. This works because methods in Scala that except a single argument can be written without parenthesis. Therefore, the standard 1 + 2 operation works as well.

Let’s talk again about loops

Now, I really do want to get back to tuples. They excited me. First, I need to illustrate further this notion of “everything as an object” (or method). Remember how in my first post, I discussed the .foreach() method of looping through an array? Guess what? There’s another way to do it using the range method. Here’s an example:

val sometext = Array("This", "is", "an", "example!")
for (i <- 0 to sometext.length-1) {
    println(blargh(i))
}

This prints:

This
is
an
example!

As in addition, this translates into two things. First, the <- operator can be read as “in.” I’m not sure if this is an actual method that is created or whether this is a genuine Scala operator. I imagine this will come clear in a few chapters. Second, the part that reads 0 to sometext.length-1 creates a range between the values of 0 and sometext.length minus one. This could also be written as: (0).to(sometext.length - 1). Or, if you really wanted additional verbosity: (0).to(sometext.length.-(1)).

So what’s this got to do with tuples?

Well, nothing much, really. (I’ll explain shortly.) Tuples, as I mentioned earlier, are simple data structures. Here’s an example of a tuple containing multiple data types as well as Scala’s output (I’m using the command line interpreter):

scala> val tup = (1, "one")
tup: (Int, java.lang.String) = (1,one)

Notice that Scala creates a tuple object containing the data types Int and java.lang.String (all data types in the JVM-version of Scala are just Java data types with some wrappers). This is handy; it’s also important to know that there exists another method: ->. Here’s the -> method at work:

scala> var tup = 1 -> "one"
tup: (Int, java.lang.String) = (1,one)

Notice that the -> operator created a tuple? Remember, too, that there is another way to write this:

scala> (1).->("one")
res41: (Int, java.lang.String) = (1,one)

(Don’t use 1.->("one") or it’ll use a Double instead of an Int.)

Here’s why this is important.

Maps use tuples. True story!

To create a Map or a HashMap in Scala, you might do something like the following:

scala> var numbers = Map[Int, String]()
numbers: scala.collection.immutable.Map[Int,String] = Map()
 
scala> numbers += 1 -> "one"
 
scala> numbers += 2 -> "two"
 
scala> numbers += 3 -> "three"
 
scala> numbers
res4: scala.collection.immutable.Map[Int,String] = Map(1 -> one, 2 -> two, 3 -> three)

See how I used the -> operator here? That’s because maps use tuples to “map” values internally. More importantly, the += operator is just a method; by default, this method will create a new map containing both the existing values and the new value (the default maps are immutable). However, if you were to type this before any of the example code (above), import scala.collection.mutable.Map, you’d wind up with a mutable version of Map in which += appends a new item to the map. Thus, here’s what the code above might look like when we’re adding new items to the map:

numbers.+=((1).->"one")

Which could also be written as:

numbers.+=((1, "one"))

And if you’re really adventurous, you could also write this to avoid having to give the compiler hints about the data types (that’s the cruft in square brackets):

var numbers = Map((1, "one"), (2 -> "two"), (3).->("three"))

That’ll cover nearly all bases! Isn’t it amazing?

A thought to leave

I’ll leave you with some thoughts for this evening. I’m very impressed with Scala so far. The syntax is a little difficult to learn for anyone coming from an imperative programming background, but the shear expressive power of Scala is dumbfounding. I’m incredibly excited by the language already, and I haven’t even touched but a small fragment of code in Programming in Scala. What’s strange is that it hasn’t been as difficult to pick up as I imagined. While I’ve run into errors, naturally, while playing around in the interactive interpreter, the errors I have created for myself are few and far between. I can’t wait to get into the Actors model of multiprocessing. I think that’s where Scala is going to truly shine. Plus, I’m intending to try it out by writing an MD5-sum generator of files on a file system (that seems to be my generic “Hello, world!” application of choice–strange!).

Anyway, I may not have another entry in this section for a couple of days. The weekend is coming up, and I have to cook for the folks as they have some guests stopping by. I’ll try an squeeze in another one on Sunday if I can’t make it Saturday. Oh, and I’ve decided that I might just skip Links of the Week this week. I know some of you really enjoy that section, so I’ll try and get something for you!

2 comments.
***

Learning Scala: Day One

I received the book Programming in Scala today. It’s an impressive text that, while weighing in at “only” 730 some-odd-pages, is chock full of examples and 33 chapters (yes, 33!). It contains about half as many pages as Programming Python and Programming Perl but don’t be fooled–the text is well written, thorough, and concise. While it may lack some of the easier to digest fluff of introductory texts, it is already proving its worth as reference material. A word of warning: This book isn’t something new programmers should consider purchasing, but if you already have another programming language under your belt it’d be a great start. Thus far, I’ve managed to make it through the introduction and the first chapter-and-a-half. Unfortunately, the prospect of writing my first post on Learning Scala was much too appealing to resist.

A couple of thoughts

First, I’d like to point out that Programming in Scala is by far one of the best programming texts I’ve encountered. It’s published by Artima Press and is written by Martin Odersky (the same guy who devised Scala), Lex Spoon, and Bill Venners. These three have created a masterful work of art. I never thought I’d say that about a programming text; really, it truly is a work of art. Suffice it to say, I’m duly impressed.

The writing style of Programming in Scala is notably academic and this is a good thing. It meshes well with one’s expectations of an instructive work and speaks to the reader in a much higher tone than other introductory texts, particularly those written by publishers who probably shouldn’t be named. More importantly, especially to the budget-conscious programmer, the book is pressed in black and white which keeps both background noise and purchase price low. There’s no fancy coloring nor flashy graphics to distract the reader from the task of learning and lots and lots of code. The book does contain some flow charts and diagrams as I’ve noticed during quick thumb-throughs after my initial excitement of opening the text (including at least one screen shot of a browser window) but it is tastefully included and most certainly not over done. This book does lack one thing in particular that many publishers seem keen on including: Obnoxious bulleted points that detract from the learning process, usually containing drawn caricatures, targeted toward individuals who would much rather be entertained than learn.

Trust me, the exclusion of flashy graphics is a good thing! I just wish that other publishers would follow the lead of Artima and O’Reilly (another great publishing house for technical works). If I ever have to suffer through another book like Java, How to Program, I think I’ll stab myself in the eye with a screw driver. Honestly, if you’re publishing a book about programming, you don’t turn it into an art studio of your favorite bee-things. It’s insulting to those of us who genuinely want to learn. Please, take a lesson from Artima and concern yourselves with content not presentation[1]. It worked well when my dad went to college. His books were text only.

Programming in Scala gives the reader exactly what they asked for: Instructions on learning how to program–in Scala. It’s amazing. Rather than wasting away pages and pages of text explaining things entirely unrelated to the language, the book dives right in. (To be fair, the first chapter gives some history and a whirlwind tour of Scala’s capabilities, and I really wish this was an idea other programming texts would borrow–they generally don’t.) While I wouldn’t recommend this book to first timers, I can most certainly see the utility in referencing this text if you’re already familiar with at least one other language (especially Java).

In case I didn’t make it clear

Programming in Scala is a superb book. I’d recommend it to anyone, and I’m only on page 33. The style of prose used in the work is outstanding. Oh, and there’s plenty of examples. If you want to learn Scala, do yourself a favor and purchase this book. You certainly won’t regret it.

Now that that’s out of the way…

Let’s talk about my initial impressions. First, I’m impressed. Scala appears to bring to the table some ideas that have been sorely lacking in a JVM-hosted language. It also appears to bind together the worlds of functional and imperative programming with object-oriented design; most importantly, everything is an object in Scala, including literals like 1. Operators aren’t implemented as a core language construct. Instead, an operator like + exists as a method implemented by the object it is applied to. So, for example, adding two numbers such as 4 + 10 will call the addition method on 4, adding 10 to its value and returning it. (The return value is also an object.)

Functions are also objects, similar in nature to Python. There is one exception, however; functions are first class citizens of the language and may be passed as arguments to other functions. It’s difficult to wrap your head around this particular concept–and I’m struggling with this bit, more on that in a moment–but think of it like this: When you’re calling a looping method on an object, you can pass in a function to that method. That function is then called, with each value passed into the function, and the call is performed. The best example I have is from page 33:

args.foreach(println)

This actually expands to:

args.foreach((arg: String) => println(arg))

Which means, roughly, “for each value of the String array args, pass it to the function println.” In the imperative world, as Programming points out on page 32, this would translate to:

var i = 0
while (i < args.length) {
    if (i != 0)
        print(" ")
    print(args(i))
    i += 1
}
println()

Clearly, the functional methods are much shorter. To the trained eye, I’m also certain they’re much clearer. The trouble is…

Functional is hard for imperative minds

The fact that functional thinking operates a bit differently from the imperative style forces a barrier upon those of us who were brought up in the imperative world. We’re used to functions doing something (also called creating “side effects” in the functional world). We’re told that if you need to loop through an array of strings, you use a language construct to assist–like foreach. Or maybe you keep track of the current offset using an index. In either case, the notion of using functions as a looping construct is almost unsettling.

I suspect this is the notion I will have the most difficulty swallowing. It certainly looks easy, but looks are deceptive. Functional languages like Erlang have a great deal of expressiveness at the cost of readability to anyone not well versed in the dark arts brought into the world by the cult of lambda calculus. I haven’t any idea what it takes to be initiated into such a cult. However, I will bet real money that I’ll be thinking about this for the first couple of weeks. It might even feel about right, too.

There’s always a light at the end of the tunnel…

The plus side is that Scala looks like a great introduction to the world of functional programming. It isn’t because the language borrows so much from Java (it does, but…), it’s because the language borrows so many great ideas from everywhere. It really does. I look forward to the “actors” model borrowed from Erlang for concurrency. It reminds me a bit of Stackless Python; message passing is an alternative solution to the multiprocessing problem. Rather than running multiple threads of execution, message passing works by allowing different actors in the same application to pass data back and forth while performing other duties. For example, if one particular actor requires inputs from three different sources, each of those sources can collect the necessary data, send it, and then go about their business to collect more. Meanwhile, the actor receiving the data blocks until it receives all three, does its processing, and then passes on the result. The collection actors have no obligation to wait until their chunk is seen to as would be the case in a single-threaded imperative language.

Of course, Java threads are available to Scala, too, so there’s quite literally a wide variety of design choices the developer can make!

…but sometimes that light is a little obscured

Scala does use some strange syntax that will definitely take some getting used to. First, variable declarations are backwards from most popular languages like Java, C, C++, Python, and Ruby. (This isn’t exactly applicable to the latter two since they’re not statically typed.) Rather than the declaration of type variable = value, Scala uses the syntax: variable:type = value. This also applies to functions which are defined as:

def functionName (arg:type, arg2:type ... argN:type):returnType = { /* function block */ }

Notice, too, that the function block occurs after an equal sign. It makes a little bit of sense in a round about way–you’re setting the function “equal” to something (its code block). To this extent, I think some syntax won’t be too difficult to follow.

Scala does have some other oddities that are simply minor aesthetic changes, though they might be familiar to those who have programmed in languages like BASIC. As in BASIC, Scala array indices are accessed via parenthesis not square brackets. Thus:

print myArray(0)

Would be valid, whereas:

print myArray[0]

Would not.

Furthermore, generics (type-hints for the compiler when declaring arrays) use square brackets instead of angled brackets. Thus, the generic (in C#):

List myList = new List<string>();

Would possibly be declared as:

var myList = List[String]()

Or even:

var myList:List[String] = List()

(I have no idea if there’s a list type, but it’s an analog that came to mind as I was typing this.)

I think this journey is going to be a fun one.

Footnotes

1: The excuse I’ve heard parroted most often is that the How to Program series are “introductory text(s).” It doesn’t really hold a lot of water for me, because I know a number of my peers who absolutely hated the stupid thing. The damn cartoons interspersed throughout Java, How to Program are insulting. There are obvious tags plastered around the book (with a bee pointing at it) that cover topics often so obvious that I know of a particular famous captain who might be looking for a new line of work.

That reminds me of a brief story related to this particular series. When I first started in the IS program at NMSU, I had the misfortune of having to purchase the sixth edition of Java, How to Program. Thankfully, I managed to used it for several of my classes. That may have mitigated much of the cost but it did little to sooth my annoyances with the cover. There, in full-color glory, was the caricature of a stereotypical college student (albeit as a bee), clearly running late, with his aunt pointing hurriedly at her wrist watch. Granted, if (IF!) you can manage to stomach the cover without succumbing to the feeling that the authors clearly think you’re too inept to read real books, the actual content isn’t bad. Although, I most certainly cannot justify full color printing for a book that’s over 1600 pages. Seriously, if you want syntax highlighting, I can think of a few solutions that happen to be free.

I confess that the work is reasonably decent for those who aren’t familiar with any programming languages. However, please realize that some college students aren’t empty headed dimwits who think computers are those funny boxes you play video games on. Some of us may have written code before. Some of us may have even had jobs. Some of us were probably a few years out of high school before we could afford to go to university. Seriously, do what a real publisher (again, like Artima and O’Reilly) does: press and publish books that actually treat the reader like a human being. Heck, even the Head First introductory series do exactly this without insulting the intelligence of the reader. Damn, even the Dummies guides manage the same thing IN SPITE OF THEIR TITLE.

Rant off.

2 comments.
***