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. For instance, in Java you'd execute a method on an object like this:

object.method();

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

object.method()

and then you can omit the parentheses:

object.method

I think you'll agree that this Scala syntax contains much less "noise" than the Java 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 wasn't completely sold on the space syntax until I ran into this Scala source 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 quite a bit, because it gets ride of the "noise" of the dot 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.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.