Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

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
  }
}
like image 446
agusgambina Avatar asked Nov 17 '16 01:11

agusgambina


1 Answers

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(c: Int, b: Int): Int = c + b
}
class MyNumber(a: Int) {
    // This depends on an instance of MyNumber
    def next: Int = a + 1
}
like image 175
radumanolescu Avatar answered Nov 15 '22 03:11

radumanolescu