Reputation: 6582
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?
Upvotes: 25
Views: 21139
Reputation: 62835
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))
Upvotes: 50
Reputation: 12158
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.
Upvotes: 20