首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >迭代case对象列表替换NaNs,并将其写回Scala

迭代case对象列表替换NaNs,并将其写回Scala
EN

Stack Overflow用户
提问于 2013-02-26 00:12:40
回答 3查看 698关注 0票数 0

我有一个case对象的List,其中一些值是NaNs,我必须用0.0替换它们。到目前为止,我尝试了以下代码:

代码语言:javascript
运行
复制
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。因此,我添加了另一个列表,但得到了一个类型不匹配:

代码语言:javascript
运行
复制
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)
  }
}

错误发生在包含+=的行上,如下所示:

代码语言:javascript
运行
复制
type mismatch;
found : scala.collection.mutable.ListBuffer[com.x.interfaces.SystemInformation]
required: com.x.interfaces.SystemInformation

为什么这不起作用?用0.0取代NaN的更好方法是什么?

EN

Stack Overflow用户

回答已采纳

发布于 2013-02-26 00:19:53

您应该使用map而不是foreach

您的第一个解决方案基本上是正确的,但是foreach只迭代所有元素,而map允许将元素从A类型映射到B,并返回一个新的B类型集合。

票数 3
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15071268

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档