在 Scala Class 定义中使用 `this`

Use of `this` in Scala Class definition

我正在阅读 Spark 书中的高级分析,在第二章中它有以下代码片段:

import org.apache.spark.util.StatCounter
class NAStatCounter extends Serializable { 
    val stats: StatCounter = new StatCounter() 
    var missing: Long = 0
    def add(x: Double): NAStatCounter = { 
        if (java.lang.Double.isNaN(x)) {
            missing += 1 
        } else { 
           stats.merge(x)
        }
        this
    }   
    def merge(other: NAStatCounter): NAStatCounter = {
        stats.merge(other.stats)
        missing += other.missing
        this
    }
    override def toString = {
        "stats: " + stats.toString + " NaN: " + missing
    }
}

这里我真的对this的使用感到困惑。在 addmerge 这两个函数中,它是指代码定义的原始 NAStatCounter 吗?

本书评论:

"The merge method incorporates the statistics that are tracked by another NAStatCounter instance into the current instance. Both of these methods return this so that they can be easily chained together."

他们说使用 this 简化链接是什么意思?

这意味着你可以做到这一点

counter.add(d1).add(d2).merge(c).add(d3)

这称为方法链接。

  1. Scala 中方法的最后一行是 return 值。这意味着您不必用多种语言说 return this; 自己的能力。
  2. 想象一下,函数(添加和合并)的参数不是另一个 NAStateCounter,而是字符串或其他一些原语可能会有所帮助。该参数与添加和合并方法 returning 的 "this" 无关。
  3. "this" 在这种情况下指向 NAStatCounter 的一个实例,所以当你说

    var nsCounter = new NAStatCounter()

add 和 merge 方法中的 "this" 指向实例,即 nsCounter。因此,例如,当您调用 add 时,它会执行其操作,然后 returns nsCounter,此时您可以调用 nsCounter 上定义的任何方法。

nsCounter.add(d1).toString()