How do I make my scala method static?

こ雲淡風輕ζ 提交于 2019-11-29 06:57:52

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 an object 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 other private 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 the class' scope, as follows:

import MyClass.doStringManipulation

class MyClass {
  def apply(myRDD: RDD[String]): Unit = {
    val rdd2 = myRDD.map(doStringManipulation)
  }
}

object MyClass {
  private def doStringManipulation(myString: String): String = {
    ???
  }
}

As a side note, for the MyClass.apply method, you used the a notation which is going to disappear in the future:

// this is a shorthand for a method that returns `Unit` but is going to disappear
def method(parameter: Type) {
  // does things
}

// this means the same, but it's going to stay
// the `=` is enough, even without the explicit return type
// unless, that is, you want to force the method to discard the last value and return `Unit`
def method(parameter: Type): Unit = {
  // does things
}

You should follow scala's advice.

val rdd2 = myRDD.map(MyClass.doStringManipulation)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!