Learning Scala: An Adventure in the Mad Unknown

One of my epic eventual goals is to teach myself enough Scala that I can follow other people’s code and maybe even get some of mine up and running. While those might seem like modest ambitions, I promise you I thought I was going crazy when I started trying out Scala late last year. So here I present to you my occasional forays into the world of the modern functional programming construct.

Philosophical constructions

When I started learning Scala, I contacted a work friend of mine who has been, as long as I’ve known him, a complete Scala obsessive. Scala is his second wife, if his first wife could tolerate the notion. So I asked him to clarify some things for me.

“What the hell is this var vs val business?” 

Turns out Scala is nuts about assuming immutability. In a disciplinary sense, this makes sense: you want to make sure, as my work friend puts it, that when you pass x to function f() and expect to get y, that no weird internal magic could change x or y. So everything in Scala is assumed to be immutable first, and mutable second. You have to actually import mutable objects if you need them.

Oddly enough — for someone coming from a Java background, anyway — all class members are publicly accessible by default. This makes sense though if you think about all variables being by default immutable — what’s someone else going to do, try to change them?

If you do it right, everything looks weird 

Okay, an exaggeration, but Scala offers a bewildering mix of Java-like verbosity and script-like conciseness.

Take the simple idea of looping through a list of numbers:

The Java-like way: while (i < nums.length)

The Scala-like way: for (i <- nums)

The Scala-like functional way: nums.foreach(println)

(Also, even stranger is the fact that in Array types, the parameter type is enclosed in [], and the array elements are accessed with (). So you would write val test = new Array[String](5).)

I’m still trying to figure out how methods work on objects, especially in things like List. Stay tuned.