Alan Coromano
Alan Coromano

Reputation: 26048

a right-associative triple colon operator

Although a triple colon is a right-associative operator, the following result says it's not true, is it?

List(3, 4, 5) ::: List(18, 19, 20) //> List[Int] = List(3, 4, 5, 18, 19, 20)

From my point of view, the result should be List(18, 19, 20, 3, 4, 5) since it's the same as saying:

List(18, 19, 20).:::(List(3, 4, 5))

Do I understand the definition of being a right-associative wrong?

Upvotes: 4

Views: 504

Answers (2)

4lex1v
4lex1v

Reputation: 21567

From the docs:

def :::(prefix: List[A]): List[A]
[use case] Adds the elements of a given list in front of this list.

Example:

List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4)
prefix  - The list elements to prepend.
returns - a list resulting from the concatenation of the given list prefix and this list.

This says it all. As for the right-associative operations, you're right.

Upvotes: 6

AmigoNico
AmigoNico

Reputation: 6862

Associativity is irrelevant in the expression

x ::: y

The associativity of ::: determines whether

x ::: y ::: z

is interpreted as (if left-associative)

( x ::: y ) ::: z

or as (if right-associative)

x ::: ( y ::: z )

Since in Scala all operators ending in a colon are right-associative, the latter interpretation is used: assuming x,y,z are variables of type List, first y is prepended to z, and then x is prepended to that.

Upvotes: 1

Related Questions