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 Responses to “Learning Scala: Day One”

  • Bahahahahaha!

    Man… what an intro! That was an amazing read to brighten up my day while I sit in my dismal comptuers class teaching other kids to press buttons in publisher… :sigh: Anyway– That was friggin’ funny and amazingly written. I might just have to use your approach to presenting the articles, instead of another way I’d planned.

  • Benjamin writes:

    Yeah, ’cause we all know that pressing buttons in an app is amazingly difficult. Sounds as if you were having a really fun day.

Leave a comment

Valid tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>