如何使我的Scala方法静态化?

B. *_*ith 9 static static-methods scala

我有一堂课

class MyClass {
  def apply(myRDD: RDD[String]) {
      val rdd2 = myRDD.map(myString => {
          // do String manipulation
      }
  }
Run Code Online (Sandbox Code Playgroud)

}

object MyClass {

}
Run Code Online (Sandbox Code Playgroud)

由于我有一段代码执行一个任务(表示的区域"do String manipulation"),因此我认为应该将其分解为自己的方法。由于该方法不会更改类的状态,因此我认为应该将其设置为static方法。

我怎么做?

我认为您可以在同伴对象内弹出一个方法,它将作为静态类提供,如下所示:

object MyClass {
  def doStringManipulation(myString: String) = {
    // do String manipulation
  }
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试时val rdd2 = myRDD.map(myString => { doStringManipulation(myString)}),scala无法识别该方法,因此它迫使我执行此操作MyClass.doStringManipulation(myString)以进行调用。

我究竟做错了什么?

ste*_*ino 11

在Scala中,没有静态方法:所有方法都是在对象上定义的,无论是类的实例还是单例,如您在问题中定义的那样。

当你正确地指出,由具有classobject在同一编译单元同样的方式命名你让该对象的同伴类,这意味着两人有获得对方的private领域和方法,但是这确实让他们可用,而无需指定要访问的对象。

您想要做的是使用提到的长格式(MyClass.doStringManipulation(myString)),或者,如果您认为有意义,则可以将方法导入到class'范围中,如下所示:

import MyClass.doStringManipulation

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

object MyClass {
  private def doStringManipulation(myString: String): String = {
    ???
  }
}
Run Code Online (Sandbox Code Playgroud)

附带说明一下,对于该MyClass.apply方法,您使用了一种将来会消失的符号:

// 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
}
Run Code Online (Sandbox Code Playgroud)