1

I have a listbuffer of events Animals. I am trying to update one of those properties.However, when using update it updates the whole element. Is there a way to update a particualr property? I'd want to update the owner for example.

import java.util.UUID

case class Car(model: String, owner: String)

var cars = new scala.collection.mutable.ListBuffer[Car]()

var car1 = Car("honda", "John")
var car2 = Car("chevy", "Xavier")
var car3 = Car("subaru", "Mario")

cars += car1
cars += car2
cars += car3

def generateRandomGuid(numOfTenants: Int) = {
  List.tabulate(numOfTenants)(_ => UUID.randomUUID().toString())
}

val ownerList = generateRandomGuid(3)

for(newowner <- ownerList) {
    for(eventIdx <- 0 to cars.length-1) {
      //cars.update(eventIdx, newowner)
     cars(eventIdx).owner = newowner 
    }  
}

Update1: updated to using var for the different cars and the list buffer to Car however, i still cannot reassign because error: reassignment to val cars(eventIdx).owner = newowner

2
  • 2
    To update a particular field, you don't have to do anything to your ListBuffer (which should be a ListBuffer[Car], btw). You'd have to mark owner with var, and then you can do cars(eventIdx).owner = newOwner Commented Nov 4, 2020 at 21:30
  • After updating that, as well as using 'var' I still cannot update the field because of reassignment to val Commented Nov 4, 2020 at 21:49

1 Answer 1

2

The short answer is that objects in Scala are immutable by default. The error you are getting (error: reassignment to val cars(eventIdx).owner = newowner) means that you cannot update the owner property of a car, because properties are immutable by default. As @nrvaller mentioned in their comment, you can declare the owner property as a variable.

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

1 Comment

I think you meant "immutable" instead of "constants" (and you did use "immutable" the first time)

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.