Kristjan Veskimäe
Kristjan Veskimäe

Reputation: 992

Calling lists concatenation in Scala

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?

Upvotes: 1

Views: 43

Answers (1)

tkachuko
tkachuko

Reputation: 1986

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.

Upvotes: 2

Related Questions