Scala - infix vs dot notation

Kevin Li picture Kevin Li · Apr 19, 2012 · Viewed 11.7k times · Source

Is there a best practice for one over the other? I've been reading the Scala book by Odersky, et al. and it seems like infix is used for a lot of the Collections API functions, whereas dot is reserved for programmer-defined functions.

Answer

missingfaktor picture missingfaktor · Apr 25, 2012

I personally do not have any hard and fast rules for this, but I tend to use infix notation only with symbolic method names, and dot notation for alphanumeric ones.

Infix notation makes it cumbersome to modify code later. Here are some examples.

Imagine you have this line of code:

xs filter { f } map { g }

Suppose at some latter point in time you need to add a toList at end. You put it so:

xs filter { f } map { g } toList

This may cause semicolon inference issues. To avoid these issues, you either put a semicolon at end, or put a new line. Both options are ugly, in my opinion. To avoid all this nonsense, I prefer to go with xs.filter(f).map(g). It's always easier to refactor with this syntax.

Another example: Say I have the following in my code:

if(foo contains bar) { ..

Say, I need to negate the condition. If I modify it as follows:

if(!foo contains bar) { ..

Bummer. This gets parsed as (!foo).contains(bar). Not what we wanted.

Or suppose you need to add a new condition in addition, and you modify it so:

if(foo contains bar && cond) { ..

Another bummer. This gets parsed as foo.contains(bar.&&(cond)). Not what we wanted, again.

Of course, you could add a bunch of parentheses around, but that would be ugly and hard to read/edit as compared with dot notation.

Now, all of what I said above applies to symbolic method names too. However symbolic methods look unnatural when used with dot syntax, and so I prefer the infix syntax for them.


One exception to the guideline above: Internal DSLs. They are usually crafted with care so as not to cause parsing issues when written in the manner prescribed in their documentation/examples (which usually uses infix notation).