ERROR : value += is not a member of Long Scala

ERROR : value += is not a member of Long Scala

我正在尝试进行一些聚合以将指标发布到 Cloud Watch。在保存最终结果之前,我添加了我的指标计数逻辑。基本上,我试图计算每列的价值 > 0 的客户数量。这样我就可以得到数字和百分比。

case class ItemData(totalRent : Long, totalPurchase: Long, itemTypeCounts: Map[String, Int] ) extends Serializable


import scala.collection.JavaConversions._


class ItemDataMetrics(startDate: String) {

  var totals: ItemData = _

  def countNonZero(c: Long): Int = {if (c > 0) 1 else 0}


  def accumulate(featureData: ItemData) {

    totals.totalRent+= countNonZero( featureData.totalRent )
    totals.totalPurchase += countNonZero( featureData.totalPurchase )

    for (entry <- featureData.itemTypeCounts.entrySet) {

      if (totals.itemTypeCounts.contains( entry.getKey )) {
        totals.itemTypeCounts.updated( entry.getKey, entry.getValue + countNonZero( entry.getValue ) )
      } else {
        totals.itemTypeCounts.put( entry.getKey, countNonZero( entry.getValue ) )
      }
    }
  }
}

 var totalCustomer : Int = 0
 val itemMetrics: ItemDataMetrics = new ItemDataMetrics(startDate)

 val resultValue = resultDF.map( {
      r => {
        val customerId = r.getAs[String]( "customerId" )

        val totalRent = r.getAs[Long]( "totalRent" )
        val totalPurchase = r.getAs[Long]( "totalPurchase" )


        val itemTypeCounts = r.getAs[Map[String, Int]]( "itemType" )


        val items = ItemData( totalRent, totalPurchase, itemTypeCounts)

        totalCustomer = totalCustomer + 1

        itemMetrics.accumulate(items)

        val jsonString = JacksonUtil.toJson( items)

        (customerId, jsonString)
      }
    } )

    publishMetrics(startDate, featureMetrics)   ---- publishes metrics to cloud watch

   resultValue.saveAsTextFile("S3:....")

但不断出现错误:

<console>:26: error: value += is not a member of Long
           totals.totalRent += countNonZero( itemData.totalRent )
                                    ^
<console>:27: error: value += is not a member of Long
           totals.totalPurchase += countNonZero( itemData.totalPurchase )

<console>:36: error: value entrySet is not a member of Map[String,Int]
           for (entry <- itemData.itemTypeCounts.entrySet) {

我是 scala/spark 的新手。有人能告诉我我做错了什么吗?

Scala中x += y有效的条件有两种:

  1. x 有一个名为 += 的方法,它将以 y 作为参数调用,或者
  2. x 是一个 var 并且有一个名为 + 的方法。在那种情况下 x 将被分配 x + y
  3. 的结果

现在Long只有+方法,没有+=方法。因此,如果 var,您只能在 Long 上使用 +=。现在您没有显示 ItemData class 的定义,但由于您遇到错误,我假设 totals.totalRentval(或 def).因此它不能被重新分配,你不能在它上面使用 +=

在 Scala 中,+= 通常接受一个可变变量 (var),为其添加一个值,然后将新值重新分配给该变量。这仅适用于 var,因为这是一个可变变量。它不适用于 val(不可变)或函数定义。

在下面的行中,totalRentval,无法重新分配。

totals.totalRent+= countNonZero( featureData.totalRent )

您可以通过在您的案例 class 变量定义中使用 var 而不是默认的 val 来解决此问题。见下文:

case class ItemData(var totalRent : Long, var totalPurchase: Long, var itemTypeCounts: Map[String, Int] ) extends Serializable

这将允许 += 重新分配。