sanaz sanaz - 7 months ago 36
Scala Question

How to append a letter to every element in an Array in scala

I have a String Array:

var z:Array[String] =Array("hand", "ball", "eye")

i want to append a "s" to every element in z ,

i am new to scala, i can print them with appending 's' :

z.foreach(arg =>println(arg +"s"))

but what i am looking for is actually change all the elements in z to have an 's'.


Depends on what you mean by "change all elements in z". Arrays are mutable containers, so you can change the data in place theoretically, even though, it's not really "scala way", and not a good idea usually:


A better way, more idiomatic and safe, way is to use map, as mentioned in the other answer:

val newZ = + "s")

This creates a copy of the array with the modified elements, leaving the original unchanged. This may become prohibitive if your array is really large, as it requires copying all of the data into a new container. For cases like that, it is a good idea to use iterators, and chain your operations into a sequence, so that only the final result is materialized. For example:

val processedData = z.iterator
 .map(_ + "s")

This does three operations on the contents of the array, but avoids creating intermediate copies after each one.