1

Can someone explain what is going on with

scala> List(1,2).:::(List(3,4))
res15: List[Int] = List(3, 4, 1, 2)

scala> List(1,2) ::: List(3,4)
res16: List[Int] = List(1, 2, 3, 4)

How can the method call results differ while they should be the same method call?

1 Answers1

2

In case of List(1,2).:::(List(3,4)) you call ::: method directly on object List(1,2). According to the docs:

@param prefix The list elements to prepend.

So you get: res15: List[Int] = List(3, 4, 1, 2)

When you do not use . (dot) notation ::: behaves as right associative operation according to the docs:

@usecase def :::(prefix: List[A]): List[A] @inheritdoc

Example: {{{List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4)}}}

That means that in the case of List(1,2) ::: List(3,4) method ::: is being called on object List(3,4).

Right associative operation means basically the following:

xs ::: ys ::: zs is interpreted as xs ::: (ys ::: zs)

Section 16.6 describes the same as example.

tkachuko
  • 1,956
  • 1
  • 13
  • 20
  • Actually found some pretty good discussions at http://stackoverflow.com/questions/1162924/what-good-are-right-associative-methods-in-scala and http://stackoverflow.com/questions/15384744/how-to-make-a-right-associative-infix-operator basically if the colon is the last element of the method name, it is right associative. So for example def mymethod:(param: MyClass) starts a right-associative method named 'mymethod:', which calls on the parameter object. – Kristjan Veskimäe Jan 13 '17 at 23:03
  • Thanks for sharing – tkachuko Jan 14 '17 at 00:26