Val
Val

Reputation: 11107

Operand order in Scala List.prepend (::)

Odersky has brilliantly optimized Java syntax, enabling object calls without dots and parenthesis. I.e. instead of list.prepend(item), you now simply write list :: item, which also turns language operators into simple object methods. Here, List defines :: (prepend) operator. However, you normally write it vice-verse in Scala, using item :: list. It suggests that every (listable) type defines the ::(List) operator, which is unbelievable. How is the operand reversal implemented? I cannot figure it out from the source code

class List[+A] extends AbstractSeq[A]
  def ::[B >: A] (x: B): List[B] =
    new scala.collection.immutable.::(x, this)

It seems that ::(val head, val tail) also stands for a type name. But it does not fit the head :: tail pattern anyway.

Upvotes: 1

Views: 406

Answers (1)

Carcigenicate
Carcigenicate

Reputation: 45826

Any operator with a : on its right side has its operands flipped. There's other operators that make use of this too (can't think of any examples off the top of my head though).

Upvotes: 4

Related Questions