agusgambina agusgambina - 20 days ago 5
Scala Question

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

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. Also that means if you instantiate the class multiple times you are allocating the same method multiple times.

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

Answer

If you remember that Scala came from Java, it may make a bit more sense. In Java, there's only a class, and it has static methods, which do not depend on any fields in an instance (but can read static fields) and regular (non-static, instance-level) methods. The distinction is between "functionality that is common to SomeType but to no instance in particular", 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 the static parts should go in the object, with the instance-level val and def being in the class. For example:

object MyNumber {
    // This does not depend on any instance of MyNumber
    def add(a: Int, b: Int): Int = a+b
}
class MyNumber(a: Int) {
    // This depends on an instance of MyNumber
    def next: Int = a + 1
}