1

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.

Val
  • 1
  • 8
  • 40
  • 64
  • `::` is Scala's "cons", the non-empty list and counterpart to `Nil`. Note that you can also use infix notation for binary type constructors - think of a generic type as a "type function" which produces a resultant type: `type \/[+A, +B] = Either[A, B]` then `def foo: String \/ Int = ???`. – J Cracknell Jun 24 '15 at 05:07

1 Answers1

4

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).

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117