我对这两段代码有什么区别有疑问。
显而易见的是,如果方法写在类中,则必须实例化该类,而如果它在伴随对象中,则不需要这样做。
但是,还有其他区别吗?有哪些好处和坏处?
在类中定义一个方法
class Hello {
def hello = println("Hello world")
}
object Hello {
def main(args: Array[String]) {
val instance = new Hello()
instance.hello
}
}
在伴生对象中定义一个方法
class Hello {
}
object Hello {
def hello = println("Hello world")
def main(args: Array[String]) {
this.hello
}
}
最佳答案
如果您还记得 Scala 来自 Java,那可能会更有意义一些。在Java中,只有一个类,它有static
方法,不依赖于实例中的任何字段(但可以读取 static
字段)和常规(非静态,实例级)方法。区别在于“对 SomeType 通用但没有特定实例的功能”和“需要特定实例状态的功能”之间的区别。前者是static
Java中的方法,后者是实例方法。在 Scala 中,所有 static
零件应该放在 object
中,与实例级别 val
和 def
在类里面。
例如:
object MyNumber {
// This does not depend on any instance of MyNumber
def add(c: Int, b: Int): Int = c + b
}
class MyNumber(a: Int) {
// This depends on an instance of MyNumber
def next: Int = a + 1
}
关于Scala 在类中定义方法而不是在伴随对象上定义方法有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40645267/