25

Scala's Map and Set define a + operator that returns a copy of the data structure with a single element appended to it. The equivalent operator for Seq is denoted :+.

Is there any reason for this inconsistency?

thesamet
  • 6,242
  • 2
  • 29
  • 41

2 Answers2

50

Map and Set has no concept of prepending (+:) or appending (:+), since they are not ordered. To specify which one (appending or prepending) you use, : was added.

scala> Seq(1,2,3):+4
res0: Seq[Int] = List(1, 2, 3, 4)

scala> 1+:Seq(2,3,4)
res1: Seq[Int] = List(1, 2, 3, 4)

Don't get confused by the order of arguments, in scala if method ends with : it get's applied in reverse order (not a.method(b) but b.method(a))

Community
  • 1
  • 1
om-nom-nom
  • 61,565
  • 12
  • 180
  • 225
20

FYI, the accepted answer is not at all the reason. This is the reason.

% scala27
Welcome to Scala version 2.7.7.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_06).

scala> Set(1, 2, 3) + " is the answer"
res0: java.lang.String = Set(1, 2, 3) is the answer

scala> List(1, 2, 3) + " is the answer"
warning: there were deprecation warnings; re-run with -deprecation for details
res1: List[Any] = List(1, 2, 3,  is the answer)

Never underestimate how long are the tendrils of something like any2stringadd.

psp
  • 12,040
  • 1
  • 39
  • 49
  • 6
    To be more clear, this is due to List being covariant, but Set being invariant, and that is the bigger problem, in my view, than any2stringadd. – Oscar Boykin May 21 '13 at 01:37