首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
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

回答 3

Stack Overflow用户

回答已采纳

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

您应该使用map而不是foreach

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

票数 3
EN

Stack Overflow用户

发布于 2013-02-26 00:24:49

建议使用map作为bluenote10,但另外,以下是什么:

代码语言:javascript
运行
复制
val transformedSystemInformation = systemInformation map (_ match {
    case s:SystemInformation if s.x.isNan() => s.copy(x = 0.0)
    case _ => _
})
票数 4
EN

Stack Overflow用户

发布于 2013-02-26 03:10:50

由于上面没有回答您的第一个问题,我想补充一句,这是不起作用的,因为+=方法

代码语言:javascript
运行
复制
def +=(x: A): ListBuffer.this.type

在这种情况下返回一个ListBuffer[SystemInformation],但您已通过类型SystemInformation参数化了foreach

代码语言:javascript
运行
复制
foreach[SystemInformation]

这就是为什么编译器需要SystemInformation类型而不是ListBuffer[SystemInformation]类型,并返回错误

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

另一方面,如果您从foreach中删除了类型参数化,您的示例将会编译:

代码语言:javascript
运行
复制
...
systemInformation.foreach { ... }
...

为了获得更好的方法,使用了Ian McMahon's建议的方法。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15071268

复制
相关文章

相似问题

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