0

How can I iterate through an array and assign its val? I tried the following two approaches but they did not work:

var a : Array[String] = Array("foo","bar")
var b : Array[String] = Array()
for (i <- 0 to (a.length-1)) {
    println(a(i))
    b :+ a(i)
}

and

var a : Array[String] = Array("foo","bar")
var b : Array[String] = Array()
for (element <- a){
    println(element)
    b :+ element
}

So the println works but they assignment doesn't.

I am really frustated since it seems so easy and I do note get it. :(

2
  • Try b = b ++ element Commented Mar 16, 2017 at 8:13
  • That doesn't work unfortunately. Commented Mar 16, 2017 at 8:46

2 Answers 2

3

Let the Standard Library do the copying for you.

val a : Array[String] = Array("foo","bar")
val b : Array[String] = a.clone()

The reason your code doesn't work is because :+ isn't an assignment operator. This statement, for example, Array() :+ "str" doesn't modify the Array, it creates a new Array with the modified value. Unfortunately your code doesn't assign that new Array to a new or existing variable so the modification is lost.

You could do something like this ...

for (element <- a){
  b = b :+ element
}

... but there are better ways to get this done.

update

To filter string elements for multiple unrelated qualities you might try this.

val acceptableRE = "(f.*|ba.*)".r
val a: Array[String] = Array("foo", "bar", "buf", "bba")
val b: Array[String] = a.collect{case acceptableRE(s) => s}   // Array(foo, bar)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer. That makes sense. Actually I do not want to clone it but apply some cases afterwards to eliminate some values of the array. Thus I am using this for loop. Or what can you suggest to do that in a better way?
So b is supposed to be a copy of a but with some values removed? If that's the case then go with Jyothi Babu Araja's suggestion and use filter (or filterNot, depending on the condition to be tested).
This would mean that I have a seperate filter for each step? Like val b = a.filter(el => el.startsWith("f")).filter(el => el.startsWith("ba"))??
Obviously not. No element will start with both "f" and "ba". See my update.
2

You can make use of .filter of Array to filter with condition.

Try this example with element length as condition

val a : Array[String] = Array("foo","bars")
val b = a.filter(el => el.length > 3)

Note: Better use val to avoid mutability.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.