Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why (copy) appending to Seq in Scala is defined as :+ and not just + as in Set and Map?

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?

like image 639
thesamet Avatar asked Sep 11 '25 09:09

thesamet


2 Answers

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

like image 65
om-nom-nom Avatar answered Sep 13 '25 06:09

om-nom-nom


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.

like image 39
psp Avatar answered Sep 13 '25 05:09

psp