1

I have an ArrayBuffer of Strings as below:

var myList = ArrayBuffer[String]()
myList += "abc"
myList += "def"

Now, I'm trying to update the String in the ArrayBuffer based on some condition:

for(item <- myList){
  if(some condition){
    item = "updatedstring"
  }
}

When I try to do this, I get an error saying val cannot be reassigned. Why do I get this error even though I have declared myList as a var? If I cannot update it this way, how else can I update the elements when iterating through the ArrayBuffer? I'm new to Scala, so I apologize if I got this all wrong.

2 Answers 2

1

The first thing I would point out is that item is not the same as myList - it's an element within myList, and the way that Scala iteration works, it's a val. There are various reasons for this related to immutability which I won't get into here.

I would recommend this instead:

val myNewList = myList.map(originalString =>
    if (someCondition) "xyz"
    else originalString
)

Then, if you feel so inclined, you could do myList = myNewList (or just forgo having a myNewList entirely and do myList = myList.map(...)).

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

Comments

1

In the for loop item is a local val. Therefore, it cannot be changed. You could:

either iterate through the array and update each item

myList.zipWithIndex foreach { case (item, index) if (condition) => myList.update(index, "updated") }

or create a new ArrayBuffer

myList = (0 until myList.length).map { index => 
  val item = myList(index)
  if (condition) "updated" else item
}

1 Comment

You could use myList.indices in your last solution, which returns the same Range as your (0 until myList.length).

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.