Scala methods: dots, spaces, and parentheses

If you’ve started using Scala, you’ve seen that there are some cool things in the Scala syntax compared to Java (and other languages). For instance, in Java you execute a method on an object like this:

object.method();

But in Scala you definitely don’t need the semi-colon:

object.method()

and you can also omit the parentheses:

object.method

Right away I think you’ll agree that this Scala syntax contains much less “noise” than Java’s syntax.

Scala single parameter methods: dots or spaces

Beyond that, if a Scala method takes a single parameter, like this:

object.method(param)

you can change the Scala syntax to use a space instead of a dot, while also dropping the parentheses:

object method param

This doesn’t look like much in that general example, but it makes for very readable code in a real world example:

pizza add pepperoni

// same as this
pizza.add(pepperoni)

or this:

order add pizza

// same as this
order.add(pizza)

Which form you use — the traditional dot syntax or the new Scala space syntax — is up to you. I don’t use the space syntax often, but I came to like it when I came across this code in the Talking Puffin project:

def main(args: Array[String]) {
    MacInit init Main.title
    UIManager setLookAndFeel UIManager.getSystemLookAndFeelClassName
    JFrame setDefaultLookAndFeelDecorated true
    launchAllSessions
}

I like this syntax because it gets ride of the “noise” of the dots and parentheses, and reads more like a sentence.

Scala dot and space syntax for single parameter methods

Again, in the end, whether you choose to use the Scala dot or space syntax is up to you (and your developer team), but the general rule bears repeating:

Scala methods that take a single parameter can be invoked without dots or parentheses.

Just remember that rule, experiment a little bit, and see which one you like better.