I have a class
class MyClass {
def apply(myRDD: RDD[String]) {
val rdd2 = myRDD.map(myString => {
// do String manipulation
}
}
}
object MyClass {
}
Since I have a block of code performing one task (the area that says "do String manipulation"
), I thought I should break it out into it's own method. Since the method is not changing the state of the class, I thought I should make it a static
method.
How do I do that?
I thought that you can just pop a method inside the companion object and it would be available as a static class, like this:
object MyClass {
def doStringManipulation(myString: String) = {
// do String manipulation
}
}
but when I try val rdd2 = myRDD.map(myString => { doStringManipulation(myString)})
, scala doesn't recognize the method and it forces me to do MyClass.doStringManipulation(myString)
in order to call it.
What am I doing wrong?
In Scala there are no static methods: all methods are defined over an object, be it an instance of a class or a singleton, as the one you defined in your question.
As you correctly pointed out, by having a
class
and anobject
named in the same way in the same compilation unit you make the object a companion of the class, which means that the two have access to each otherprivate
fields and methods, but this does make they are available without specifying which object you are accessing.What you want to do is either using the long form as mentioned (
MyClass.doStringManipulation(myString)
) or, if you think it makes sense, you can just import the method in theclass
' scope, as follows:As a side note, for the
MyClass.apply
method, you used the a notation which is going to disappear in the future:You should follow scala's advice.
val rdd2 = myRDD.map(MyClass.doStringManipulation)