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.
:: - 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.
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.
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.
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.
+= 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):
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With