我有一个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类型集合。
发布于 2013-02-26 00:24:49
建议使用map作为bluenote10,但另外,以下是什么:
val transformedSystemInformation = systemInformation map (_ match {
case s:SystemInformation if s.x.isNan() => s.copy(x = 0.0)
case _ => _
})发布于 2013-02-26 03:10:50
由于上面没有回答您的第一个问题,我想补充一句,这是不起作用的,因为+=方法
def +=(x: A): ListBuffer.this.type在这种情况下返回一个ListBuffer[SystemInformation],但您已通过类型SystemInformation参数化了foreach
foreach[SystemInformation]这就是为什么编译器需要SystemInformation类型而不是ListBuffer[SystemInformation]类型,并返回错误
type mismatch;
found : scala.collection.mutable.ListBuffer[com.x.interfaces.SystemInformation]
required: com.x.interfaces.SystemInformation另一方面,如果您从foreach中删除了类型参数化,您的示例将会编译:
...
systemInformation.foreach { ... }
...为了获得更好的方法,使用了Ian McMahon's建议的方法。
https://stackoverflow.com/questions/15071268
复制相似问题