代码之家  ›  专栏  ›  技术社区  ›  B. Smith

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

  •  21
  • B. Smith  · 技术社区  · 7 年前

    我有课

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

    }

    object MyClass {
    
    }
    

    因为我有一块代码执行一个任务 "do String manipulation" ),我想我应该把它变成自己的方法。由于该方法没有改变类的状态,所以我认为应该将其设置为 static 方法

    我该怎么做?

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

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

    但是当我尝试的时候 val rdd2 = myRDD.map(myString => { doStringManipulation(myString)}) ,scala无法识别该方法,这迫使我 MyClass.doStringManipulation(myString) 为了给它打电话。

    我做错了什么?

    3 回复  |  直到 4 年前
        1
  •  31
  •   stefanobaghino    4 年前

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

    正如你正确指出的那样 class object 在使对象成为 同伴 这意味着这两个人可以访问彼此的 private 字段和方法,但这确实意味着它们在不指定要访问的对象的情况下可用。

    您要做的是使用前面提到的长表单( MyClass.doStringManipulation(myString) )或者,如果您认为有意义,您可以在 '范围,如下所示:

    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 方法,您使用了将来将消失的a表示法:

    // 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
    }
    
        2
  •  3
  •   Joaquín Bucca    7 年前

    你应该听从scala的建议。

    val rdd2 = myRDD.map(MyClass.doStringManipulation)

        3
  •  1
  •   Shubham Gupta    4 年前

    在类中编写此内容,然后它将按预期工作。

    import MyClass._