0

I'm pretty new to Scala programming and now trying to understand the exact behavior of the operator + for the scala.collection.immutable.List. Here is what I wrote:

val _1 = List(1, 2) println((_1 + "2") foreach print 

I couldn't write the following

_1 + 2 //error: expected String 

That's clear, because we're trying to execute the + operator defined within the String class.

But what is not clear it's why they didn't just override the operator + for the List, but instead defined operator ++ for concatenating?

Was there some technical reason for that?

What does that mean?

8
  • I think it is a design flaw of the Scala authors to make + attached to Strings. Commented Jul 20, 2015 at 17:23
  • What do you mean by "operator + for the List"? scala.ollection.immutable.List does not provide the + operator. And what you want would be :+ instead of + or ++. Commented Jul 20, 2015 at 17:26
  • @yanana I know. That's exactly what I was confused by. What was the reason for not providing an overriden version for List? Commented Jul 20, 2015 at 17:27
  • 1
    There is a + for everything convertible to String. So the List is first converted to String and then there is a + operator. Commented Jul 20, 2015 at 17:27
  • 4
    IMHO, to provide a + operator to the List-like data structure is just a bad habit as the + operation in mathematics is commutative, but List nor even String is not. Commented Jul 20, 2015 at 17:43

1 Answer 1

2

why they didn't just override the operator + for the List, but instead defined operator ++ for concatenating?

Methods that take not individual elements but collections usually indicate that by a "plural" operator, e.g. ++ to concatenate collections, ::: to prepend lists. The + method is for example used to add individual elements to non-linear collections Set and Map:

Set(1, 2, 3) + 4 Map(1 -> "foo", 2 -> "bar") + (3 -> "baz") 

And in "plural":

Set(1, 2, 3) ++ Set(4, 5, 6) 

Linear collections indicate the "direction" by adding a colon, so :+ for append and +: for prepend:

1 +: Seq(2, 3) :+ 4 

Was there some technical reason for that?

No. It is possible to define the + method on any type for any reason. It is just not advised.


List(1, 2) + "3" // "List(1, 2)3" 

This is a common puzzler in Scala. If the right hand operand is a String, there is an implicit conversion of the left operand to another String using the toString method, glueing the two strings together.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.