Home > Blockchain >  Does Scala's immutability mean the list can't be modified or the list and its contents can
Does Scala's immutability mean the list can't be modified or the list and its contents can

Time:11-23

I'm learning Scala and function programming and its immutability concept.

If my code operates on a list of objects like this:

class Devices(
  val devices_df: Dataset[Row],
){
  private lazy val _devices = _initialize_list_of_devices()

  def devices(): List[Device] = {
    _devices
  }

  private[this] def _initialize_list_of_devices(): List[Device] = {
    val devices_list = ListBuffer[Device]()
    for (device <- devices_df.collect()) {
      devices_list  = new Device(
        device.getAs[String]("DeviceName"),
      )
    }
    devices_list.toList
  }
}

And I initialize the list like this:

  val devices_list = new Devices(devices_df).devices()

And then later on, I update the objects in the list like this:

  for (device <- devices_list) {
    device.modify_instance_properties()
  }

The code works and I am able to modify the objects within the list.

However, when I try to add another object to the list with something like this:

devices_list  = new Device("append another device")

it fails whether it is val devices_list or var devices_list.

I just want to sanity check that I am not misunderstanding things and want to confirm that these are true:

  • immutability does not mean the objects in the list cannot be modified
    • the objects seem to be updating their properties just fine
  • immutability does mean the list cannot be changed
    • I am supposed to not be able to add another object to the list or remove an existing object from the list

Thank you for your time and help

  • Related