MaatDeamon MaatDeamon - 7 months ago 42
Scala Question

Understanding Scala Notation syntax

I have the following code:

abstract class AList {
def head:Int
def tail:AList
def isEmpty:Boolean
def ::(n: Int): AList = SimpleList(n, Empty)

object Empty extends AList {

def head = throw new Exception("Undefined")

def tail = throw new Exception("Undefined")

def isEmpty = true


case class SimpleList(head: Int, tail: AList = Empty) extends AList {

def isEmpty = false


1 :: 2 :: Empty

I wonder how the last line actually works. There is no implicit conversion from Int to SimpleList. Hence I do not understand the method call mechanism.


I do not see that pattern here. I think a clarification of scala notation (infix, suffix, postfix, etc...) would help. I'd like to understand the syntactic sugar.



:: is a method of the right operand. In scala if a method name ends in a colon the method is invoked on the right operand. So 1 :: 2 :: Empty is actually Empty.::(2) which returns a SimpleList.

The subsequent 1 :: <the-new-simple-list> is easy to follow once you understand that :: is a method of the right operand.