Right associativity in Scala

We define two methods here, ++ and ++:

1
2
3
4
5
6
7
8
9
10
11
class Foo {
def ++(n: Int): Unit = println(n + 1)
def ++:(n: Int): Unit = println(n + 1)
}
object ValFunctionTest {
def main(args: Array[String]): Unit = {
val foo = new Foo
foo.++(1)
foo.++:(1)
}
}

Nothing special, right? Yes, for now, until we try removing the parentheses in it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Foo {
def ++(n: Int): Unit = println(n + 1)
def ++:(n: Int): Unit = println(n + 1)
}
object ValFunctionTest {
def main(args: Array[String]): Unit = {
val foo = new Foo
foo ++ 1
1 ++: foo

foo ++: 1 // error
1 ++ foo // error
}
}

So the difference is, foo can only be placed on the left side when using ++, and it can only be placed on right side when using ++:. The latter is called right associativity, and methods ending with : are used in the right associativity.

Share