Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: understanding the ::: operator

Tags:

scala

Is it true that applying the list1 ::: list2 operator to two lists corresponds to appending all of the contents of list1 to list2?

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

scala> val b = List(4,5,6)
b: List[Int] = List(4, 5, 6)

scala> a:::b
res0: List[Int] = List(1, 2, 3, 4, 5, 6)

Is there any other use for this operator? I could not find anything on ::: in the Scala documentation and am wondering the extent of its formal name and use.

like image 608
rookie Avatar asked Oct 15 '14 05:10

rookie


People also ask

What does ::: mean in Scala?

:: - adds an element at the beginning of a list and returns a list with the added element. ::: - concatenates two lists and returns the concatenated list.

What's the difference between ++ and ::: in Scala?

The difference is in the types that they accept. ::: only accepts a List . ++ accepts is a range of types from [B >: A, That] meaning that ++ will accept a type whose lower bound is List and upper bound is GenTraversableOnce[B] and types in between. Also, see Kim's note about associativity.

How do operators in Scala work?

In Scala, all operators are methods. Operators themselves are just syntactic sugar or a shorthand to call methods. Both arithmetic addition (+) and String. charAt() are examples of infix operators.

What does :+ mean in Scala?

On Scala Collections there is usually :+ and +: . Both add an element to the collection. :+ appends +: prepends. A good reminder is, : is where the Collection goes. There is as well colA ++: colB to concat collections, where the : side collection determines the resulting type.

Can you do += in Scala?

+= and similar operators are desugared by the compiler in case there is a + defined and no += is defined. (Similarly works for other operators too.) Check the Scala Language Specification (6.12. 4):


1 Answers

Yes, it is just the list concatenation operator. They are nil terminated linked lists so conceptually all it is really doing is taking the last cons cell of the first list and pointing it to the head of the second list instead of Nil.

You can also use the more generic ++ operator instead of ::: if you prefer. The end result is the same but technically you are making calls on different objects. Operators ending in a : are right associative in Scala so using a ++ b is the same as a.++(b) or basically a.append(b) as opposed to a ::: b being right associative is translated to b.:::(a) which can be read as b.prepend(a).

like image 69
Shane Delmore Avatar answered Nov 09 '22 07:11

Shane Delmore