Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lists in Scala - plus colon vs double colon (+: vs ::)

Tags:

scala

I am little bit confused about +: and :: operators that are available.

It looks like both of them gives the same results.

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

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

scala> 0 :: res0
res2: List[Int] = List(0, 1, 2, 3)

For my novice eye source code for both methods looks similar (plus-colon method has additional condition on generics with use of builder factories).

Which one of these methods should be used and when?

like image 897
Marek J Avatar asked Dec 27 '16 14:12

Marek J


People also ask

What does double colon mean in Scala?

The double colon ( :: ) is the cons operator; x represents the head of the list, and xs the tail.

What does ++ mean in Scala?

++= can mean two different things in Scala: 1: Invoke the ++= method. In your example with flatMap , the ++= method of Builder takes another collection and adds its elements into the builder. Many of the other mutable collections in the Scala collections library define a similiar ++= method.

What is the colon used for in Scala?

First thing is that, in the strict sense, Scala does not have operators. It only has methods defined on objects. And when a Symbol (that is, a method name) ends with a colon, it means it is actually defined on the right operand, instead of it being a method on the left operand.

What is a double colon used for?

The double colon ( :: ) may refer to: an analogy symbolism operator, in logic and mathematics. a notation for equality of ratios. a scope resolution operator, in computer programming languages.


1 Answers

+: works with any kind of collection, while :: is specific implementation for List. If you look at the source for +: closely, you will notice that it actually calls :: when the expected return type is List. That is because :: is implemented more efficiently for the List case: it simply connects the new head to the existing list and returns the result, which is a constant-time operation, as opposed to linear copying the entire collection in the generic case of +:.

+: on the other hand, takes CanBuildFrom, so you can do fancy (albeit, not looking as nicely in this case) things like:

val foo: Array[String] = List("foo").+:("bar")(breakOut)

(It's pretty useless in this particular case, as you could start with the needed type to begin with, but the idea is you can prepend and element to a collection, and change its type in one "go", avoiding an additional copy).

like image 156
Dima Avatar answered Sep 30 '22 03:09

Dima