Giovanni Botta
Giovanni Botta

Reputation: 9816

Scala prepending to ListBuffer puzzler

Using Scala 2.10.3. The following code works for me:

val sequence = new ListBuffer[Int]()
sequence.+=:(x)

but if I write:

val sequence = new ListBuffer[Int]()
sequence +=: x

I get:

value +=: is not a member of Int
  sequence +=: x
       ^

What am I missing?

Upvotes: 3

Views: 117

Answers (3)

Anthony Accioly
Anthony Accioly

Reputation: 22461

+=: is a prepend operator (like :: for immutable Lists) so it makes sense to be right associative

1 +=: 2 +=: 3 +=: ListBuffer() += 4 += 5 += 6
  //  ListBuffer(1, 2, 3, 4, 5, 6)

Upvotes: 1

Kevin Wright
Kevin Wright

Reputation: 49705

Any operator ending in : is right-associative.

So when you write:

sequence +=: x

It gets parsed as:

x.+=:(sequence)

Which of course fails, because x doesn't have a +=: method

Upvotes: 4

Lee
Lee

Reputation: 144136

In Scala, methods ending in a colon are invoked on the right argument instead of the left, so your second example is

x.+=:(sequence)

which fails since Int has no such operator.

Upvotes: 1

Related Questions