如何在 Scala 中将方法限定为静态方法?

How to qualify methods as static in Scala?

我有一个class

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

}

object MyClass {

}

因为我有一段代码执行一个任务("do String manipulation" 区域),我想我应该把它分解成它自己的方法。由于该方法没有改变 class 的状态,我认为我应该将其设为 static 方法。

我该怎么做?

我认为您可以在伴随对象中弹出一个方法,它可以作为静态方法使用 class,如下所示:

object MyClass {
  def doStringManipulation(myString: String) = {
    // do String manipulation
  }
}

但是当我尝试 val rdd2 = myRDD.map(myString => { doStringManipulation(myString)}) 时,scala 无法识别该方法,它迫使我必须执行 MyClass.doStringManipulation(myString) 才能调用它。

我做错了什么?

你应该听从 scala 的建议。

val rdd2 = myRDD.map(MyClass.doStringManipulation)

Scala 中没有 static 方法:所有方法都是在一个对象上定义的,无论是 class 的实例还是单例,就像你在你的问题中定义。

正如您正确指出的那样,通过在同一编译单元中以相同方式命名一个 class 和一个 object,您可以使对象成为 companion 的 class,这意味着两者可以访问彼此的 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 = {
    ???
  }
}

附带说明一下,对于 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
}

将此写在 class 中,然后它将按预期工作。

import MyClass._