Scala what is the difference between defining a method in a class instead on a companion object

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 } } 
+5
source share
1 answer

If you remember that Scala came with Java, this might make a little more sense. Only a class exists in Java, and it has static methods that are independent of any fields in the instance (but can read static fields) and ordinary (non-static, instance-level) methods. The difference lies in “functionality that is common to SomeType but not in any instance” and “functionality that needs the state of a particular instance”. The former are static methods in Java, and the latter are instance methods. In Scala, all static parts must be in object , and the class has a class val and def . For instance:

 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 } 
+7
source

Source: https://habr.com/ru/post/1259870/


All Articles