Why Array's :+ does not work inside for comprehension?

append, arrays, scala

Solution

You need to understand the :+ operator. Rather than modifying the existing trimmedTagsArray variable, the :+ is actually returning a new array with the result of the expression "tag.trim" appended to the end. Since you neither yield this result back, or assign it anywhere, this value is discarded.

I believe what you are actually looking for is to replace the line in your for comprehension with the following.

trimmedTagArray = trimmedTagArray :+ tag.trim

While this will accomplish what you want, however, it is not the best solution by far. Instead, try the following...

val trimmedTagsArray = for(tag <- tagsArray) yield {
  tag.trim
}

The above will create a val (preferred in Scala over var) that has the desired values while avoiding mutable state.

Problem

``` val tagsArray = tags.split(",") var trimmedTagsArray: Array[String] = Array() for(tag <- tagsArray) { trimmedTagsArray :+ tag.trim } ``` trimmedTagsArray is empty afterwards, even though tagsArray contains elements, and even if I omit the trim call. What am I missing here?

Original source