The expression 2::1
is interpreted in Scala as:
{ val x = 2; 1.::(x) }
because operators ending in a colon :
are right-associative and if op
is right-associative, then e1 op e2
is interpreted as { val x = e1; e2.op(x) }
(see Scala Language Reference, Section 6.12.3, p. 84, which is p. 92 of the PDF).
For the purposes here, basically the following simplified version is called
1.::(2)
However, 1
is of type Int
and Int
does not have a method with name ::
(and there is also no implicit conversion to another type that has such a method), hence the error.
As ayvango has pointed out above, you could use
2::1::Nil
which is interpreted as
Nil.::(2).::(1)
Now this works perfectly well, because Nil
is of type List[Nothing]
and does have a method ::
, see scala.collection.immutable.List Furthermore, ::
returns something of type List[Int]
, so the subsequent call .::(1)
is also fine.
Another way is
2::List(1)
which becomes List(1).::(2)
and works for the same reason as above.
Your confusion might be due to the fact that you consider List(2,1)
to be the same as 2::1
, however, it is actually 2::1::Nil
. Think of lists as being built inductively as follows:
Nil
is a list
- if
head
is an element and tail
is a list, then head::tail
is a list
as witnessed by the implementation of lists (simplified version, omitting traits)
sealed abstract class List[+A]
final case class ::[B](head: B, tl: List[B]) extends List[B]
object Nil extends List[Nothing]
Thus, lists always "end with" Nil
in the ::
form of presentation.
On a sidenote, you could also try to automatically wrap Int
into List[Int]
by using something like
implicit def wrap(x : Int) : List[Int] = List(x)
or use similar functionalities provided by libraries such as Scalaz but this might not always be desirable and probably is a bit beyond the scope of this question.