32

I saw some Scala code written as:

 def next(): Array[String] = someVariable.next() :+ iterator.key 

Where someVariable has a method next() to get the next line and the iterator is of type Iterator[String].

What does :+ mean here?

3
  • 3
    Is there some reason why you didn't just look this up in the scala doc? scala-lang.org/api/2.11.8/… The API documentation is fairly comprehensive, and my "go to" place for questions like this. Commented May 12, 2016 at 15:23
  • It's cool new docs (2.12) give you this nice search feature scala-lang.org/files/archive/api/2.12.0-M4/index.html?search=:+ Commented May 12, 2016 at 20:12
  • @TheArchetypalPaul the time you took to write this stuff, could have answered him in a better way... Commented May 16, 2018 at 20:12

3 Answers 3

48

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. If a :++ exists, it is the same as ++. In both cases the left side collection determines the type of result.

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

1 Comment

What is difference between ++ and :++?
30

:+ is a method on whatever type is returned by someVariable.next().

Presumably it's scala.Array.:+

A copy of this array with an element appended.


This is also a case where an IDE would help you greatly. With Intellij for example, you could use the "Quick doc" or "Jump to definition" commands on :+ and immediately find out where it came from. I've found that tooling to be invaluable in writing scala.

Comments

5
scala> List(1,2,3,4) :+ 400 res27: List[Int] = List(1, 2, 3, 4, 400) 

2 Comments

While this code may solve the question, including an explanation really helps to improve the quality of your post.
And with questions this old it can be quite helpful to explain how your answer is different from the existing answers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.