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
.
Question
I have a List
of case objects of which some values are NaN
s 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 NaN
s with 0.0
?
Solution 2
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
.
OTHER TIPS
Use map as bluenote10 sugested, but additionally, what about:
val transformedSystemInformation = systemInformation map (_ match {
case s:SystemInformation if s.x.isNan() => s.copy(x = 0.0)
case _ => _
})
Since your first question is not answered above, I thought I would add that this doesn't work, because the method +=
def +=(x: A): ListBuffer.this.type
returns a ListBuffer[SystemInformation]
in this case, but you have parameterized foreach
by the type SystemInformation
foreach[SystemInformation]
which is why the compiler is expecting the type SystemInformation
rather than ListBuffer[SystemInformation]
and returns the error
type mismatch;
found : scala.collection.mutable.ListBuffer[com.x.interfaces.SystemInformation]
required: com.x.interfaces.SystemInformation
If, on the other hand, you remove the type parameterization from foreach, your example will compile:
...
systemInformation.foreach { ... }
...
For a better approach, used Ian McMahon's suggested approach.