我有一个case对象的List,其中一些值是NaNs,我必须用0.0替换它们。到目前为止,我尝试了以下代码:
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)
}
}但这并不会将更改写回systemInformation。因此,我添加了另一个列表,但得到了一个类型不匹配:
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)
}
}错误发生在包含+=的行上,如下所示:
type mismatch;
found : scala.collection.mutable.ListBuffer[com.x.interfaces.SystemInformation]
required: com.x.interfaces.SystemInformation为什么这不起作用?用0.0取代NaN的更好方法是什么?
发布于 2013-02-26 00:19:53
您应该使用map而不是foreach。
您的第一个解决方案基本上是正确的,但是foreach只迭代所有元素,而map允许将元素从A类型映射到B,并返回一个新的B类型集合。
https://stackoverflow.com/questions/15071268
复制相似问题