I have a doubt about what is the difference between this two pieces of code.
The obvious ones are that if the method is written in the class you must instantiate the class, while if it is in the companion object, you are not required to do that.
However, Are there also other differences? Which are the benefits and drawbacks?
define a method in the class
class Hello {
def hello = println("Hello world")
}
object Hello {
def main(args: Array[String]) {
val instance = new Hello()
instance.hello
}
}
define a method in the companion object
class Hello {
}
object Hello {
def hello = println("Hello world")
def main(args: Array[String]) {
this.hello
}
}