7

Why in Scala 2.12.6 does Array("1") ++ "-3" output res1: Array[Any] = Array(1, -, 3)?

How do I get the result Array("1", "-3")?

5
  • Array("1") ++ Array("-3") Oct 10, 2018 at 11:43
  • should i use ":+"? if the second part is a String
    – Archer
    Oct 10, 2018 at 11:50
  • That's one way of doing it. Oct 10, 2018 at 11:53
  • 1
    The ++ method concatenates two sequences. String isn't a sequence, so Scala applies an implicit conversion, i.e. transforms it to a sequence of chars.
    – insan-e
    Oct 10, 2018 at 13:04
  • This still kind of blows my mind Nov 15, 2018 at 18:12

5 Answers 5

8

The ++ operator concatenates two Lists (or other collections) together. As a String is essentially just a list of Chars, as @senjin.hajrulahovic points out the compiler treats it this way (and returns an Array[Any].

You can get around this in multiple ways. For example, Array("1") ++ Array("-3") (to add two arrays together) or Array("1") :+ "-3" to put the value on the end of the Array.

3

++ is binary operator(also called method) that is used to concatenate two collections.eg. Arrays or Lists. If the first operand is an Array, the result defaults to Array. If the first operand is a List, the result defaults to List.

The compiler, by default, treats "-3" as String. All Strings can be treated as collections also (by implicit conversions when required ). But what type of collection? Is it Array? Is it List? depends on its usage with the type of collection it is operated on.

For Example, While using it as Array("1") ++ "-3", the String "-3" by default will be treated by the compiler as Array[Char] because the first operand of ++ is an Array ( though the type of elements will be always Char by default , by the compiler) While using it as List("1") ++ "-3", the String "-3" by default will be treated as List[Char] because the first operand of ++ is a List ( though the type of elements will be always Char by default , by the compiler)

When the ++ operator encounters both operands are collections of different types of elements, their closest super-type in type-hierarchy, will be the type of elements of the resultant collection. The super-type of String, which is the type of elements of first operand(collection) and Char, which is the type of elements of second operand(collection) is Any. So the result of Array("1") ++ "-3" is Array[Any].

If you want to add the String "-3" as an element to the collection, Array("1"), then you must add it as an element to this collection. There is another method ie., :+ or +: to append or prepend an element to the collection as below.

To append to the collection:

scala> Array("1") :+ "-3"
res6: Array[String] = Array(1, -3)

To prepend to the collection:

scala> "-3" +: Array("1")
res7: Array[String] = Array(-3, 1)

Another way of doing the above is as below(converting element to a collection and using ++ method):

scala> Array("1") ++ Array("-3")
res9: Array[String] = Array(1, -3)

scala> Array("-3") ++ Array("1")
res10: Array[String] = Array(-3, 1)

scala>
3

Because scala treats "-3" as a sequence of chars '-' and '3'.

If you want to append the string "-3" as one element use :+.

2
  • should i use ":+"?
    – Archer
    Oct 10, 2018 at 11:49
  • Yes. It returns the result you want to achieve. Oct 10, 2018 at 11:51
2

Finally I found the explanation here.

The following is an excerpt (verbatim) from there.

How to add (append and prepend) elements to an Array

You can’t resize a Scala Array, but you can use these operators (methods) to append and prepend elements to an array while assigning the result to a new variable:

┌──────────────────────────┬─────────────────┬──────────────────────────────┐
│ Method                   │  Description    │  Example                     │
├──────────────────────────┼─────────────────┼──────────────────────────────┤
│ :+                       │ append 1 item   │ oldArray :+ e                │
├──────────────────────────┼─────────────────┼──────────────────────────────┤
│ ++                       │ append N items  │ oldArray ++ newArray         │
├──────────────────────────┼─────────────────┼──────────────────────────────┤
│ +:                       │ prepend 1 item  │ e +: oldArray                │
├──────────────────────────┼─────────────────┼──────────────────────────────┤
│ ++:                      │ prepend N items │ newArray ++: oldArray        │
└──────────────────────────┴─────────────────┴──────────────────────────────┘

Append and prepend examples

These examples show how to use those methods to append and prepend elements to an Array:

val v1 = Array(4,5,6)         // Array[Int] = Array(4, 5, 6)
val v2 = v1 :+ 7              // Array(4, 5, 6, 7)
val v3 = v2 ++ Array(8,9)     // Array(4, 5, 6, 7, 8, 9)

val v4 = 3 +: v3              // Array(3, 4, 5, 6, 7, 8, 9)
val v5 = Array(1,2) ++: v4    // Array(1, 2, 3, 4, 5, 6, 7, 8, 9)
0
0

I have a tip here that has helped me. To remember what "append" operators do what, think of :+ or +:, which append one element to a list, as it being "the side of the operator that is the colon side - is the 'collection' side." This tells you which operand represents what and also that there is a reason to differentiate.

1
  • 1
    I imagine the colon as glue and the plus as a pointy thing the element is skewered on. (Well, it helps me.)
    – Seth Tisue
    Oct 10, 2018 at 17:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.