Reputation: 3
While learning Scala, I came across interesting concept of companion object. Companion object can used to define static methods in Scala. Need few clarifications in the below Spark Scala code in regard of companion object.
class BballStatCounter extends Serializable {
val stats: StatCounter = new StatCounter()
var missing: Long = 0
def add(x: Double): BballStatCounter = {
if (x.isNaN) {
missing += 1
} else {
stats.merge(x)
}
this
}
}
object BballStatCounter extends Serializable {
def apply(x: Double) = new BballStatCounter().add(x)
}
Above code is invoked using val stat3 = stats1.map(b=>BballStatCounter(b))
.
stats
and missing
declared in the
class? Is it similar to class attributes of Python? apply
method in here?Upvotes: 0
Views: 1223
Reputation: 27421
stats
and missing
are members of the class BcStatCounter
. stats
is a val
so it cannot be changed once it has been defined. missing
is a var
so it is more like a traditional variable and can be updated, as it is in the add
method. Every instance of BcStatCounter
will have these members. (Unlike Python, you can't add or remove members from a Scala object)
The apply
method is a shortcut that makes objects look like functions. If you have an object x
with an apply
method, you write x(...)
and the compiler will automatically convert this to x.apply(...)
. In this case it means that you can call BballStatCounter(1.0)
and this will call the apply
method on the BballStatCounter
object.
Neither of these questions is really about companion objects, this is just the normal Scala class framework.
Please note the remarks in the comments about asking multiple questions.
Upvotes: 0
Reputation: 56
Here stats and missing
are class attributes and each instance of BballStatCounter will have their own copy of them just like in Python.
In Scala the method apply
serves a special purpose, if any object has a method apply and if that object is used as function calling notation like Obj() then the compiler replaces that with its apply method calling, like Obj.apply() .
The apply method is generally used as a constructor in a Class Companion object. All the collection Classes in Scala has a Companion Object with apply method, thus you are able to create a list like : List(1,2,3,4)
Thus in your above code BballStatCounter(b) will get compiled to BballStatCounter.apply(b)
Upvotes: 2