0

From the official documentation

Companion objects are used for methods and values that are not specific to instances of the companion class. For instance, in the following example the class Circle has a member named area which is specific to each instance, and its companion object has a method named calculateArea that’s (a) not specific to an instance, and (b) is available to every instance:

and the official example given is

import scala.math.*

class Circle(val radius: Double):
  def area: Double = Circle.calculateArea(radius)

object Circle:
  private def calculateArea(radius: Double): Double = Pi * pow(radius, 2.0)

I cannot get the point (b) to work:

import scala.math.*

class Circle(val radius: Double):
  def area: Double = Circle.calculateArea(radius)

object Circle:
  private def calculateArea(radius: Double): Double = Pi * pow(radius, 2.0)
@main def f() = {
  val t1 = Circle(1)
  t1.calculateArea(4) <-- compilation error calculateArea is not a member of Circle
}

What am I missing here?

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
figs_and_nuts
  • 4,870
  • 2
  • 31
  • 56

1 Answers1

4

Scala is not Java. You can't call class static methods on class instances as instance methods i.e. you can't call methods of companion object on class instances. A class and its companion object are different classes/types

Class companion object vs. case class itself

its companion object has a method named calculateArea that’s (a) not specific to an instance, and (b) is available to every instance:

(b) means just that private members of companion object (e.g. calculateArea) are accessible in the class and private members of the class are accessible in the companion object. Private members of a class and its companion object are not accessible outside the class and its companion object (e.g. in @main).

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66