Search code examples
scalapattern-matchingcase-classtype-mismatch

Iterate through List of case objects replace NaNs and write it back in Scala


I have a List of case objects of which some values are NaNs and I have to replace them with 0.0. So far I tried this code:

var systemInformation: List[SystemInformation] = (x.getIndividualSystemInformation)

systemInformation.foreach[SystemInformation] {
  _ match {
    case SystemInformation(a, b, c, d, e, f, g, h, i, j, k, l, m, x) if x.isNaN()
      => SystemInformation(a, b, c, d, e, f, g, h, i, j, k, l, m, 0.0)
    case SystemInformation(a, b, c, d, e, f, g, h, i, j, k, l, m, x) if !x.isNaN()
      => SystemInformation(a, b, c, d, e, f, g, h, i, j, k, l, m, x)
  }
}

But that does not write the changes back to systemInformation. So I added another List but got a type mismatch:

var systemInformation: List[SystemInformation] = (x.getIndividualSystemInformation)

var systemInformationWithoutNans: ListBuffer[SystemInformation] = new ListBuffer[SystemInformation]
systemInformation.foreach[SystemInformation] {
  _ match {
    case SystemInformation(a, b, c, d, e, f, g, h, i, j, k, l, m, x) if x.isNaN()
      => systemInformationWithoutNans += SystemInformation(a, b, c, d, e, f, g, h, i, j, k, l, m, 0.0)
    case SystemInformation(a, b, c, d, e, f, g, h, i, j, k, l, m, x) if !x.isNaN()
      => SystemInformation(a, b, c, d, e, f, g, h, i, j, k, l, m, x)
  }
}

The error occurs on the line with the += and is the following:

type mismatch;
found : scala.collection.mutable.ListBuffer[com.x.interfaces.SystemInformation]
required: com.x.interfaces.SystemInformation

Why does this not work? What would be a better way to replace the NaNs with 0.0?


Solution

  • You should use map instead of foreach.

    Your first solution is basically the right way to go, but foreach only iterates over all elements, whereas map allows to map the elements from type A to B returning a new collection of type B.