I have doubts about the difference between the two pieces of code.
The following are obvious: if the method is written in the class, you must create an instance of the class, and if it is in the companion object, you are not required to do this.
However, are there other differences? What are the advantages and disadvantages?
define a method in a 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 a companion object
class Hello { } object Hello { def hello = println("Hello world") def main(args: Array[String]) { this.hello } }
source share