Scala A companion Object Vs. Scala Class new Object

263 views Asked by At

Here is the code and the output:

//A scala class with a private variable and one method
class A {
  private var a1 = "Zoom"
  def A1(): Unit = {
    println("A1 Class")
  }
}

//A companion object
object A {

  def A2(): Unit = {
    println("A1 Obj")
    val objA = new A
    objA.A1()
    println("a1 -> "+ objA.a1)
  }
}

Output
======
A1 Obj
A1 Class
a1 -> Zoom

Now my doubt is if I don't wanna use new operator to create an Object of A class how can A companion object will print a1(private variable) value and also access the A1 method of A class. I mean to say I wanna access both the members of Companion Class A through the companion object A.

//A companion object
object A {

  def A2(): Unit = {
    println("A1 Obj")

    A.A1()  //It should print A1 Class

    println("a1 -> "+ A.a1) //It should print Zoom
  }
}

The above code snippet should also work fine because in Mardin Odersky's book it has been written that A class and its companion object can access each other’s private members.

1

There are 1 answers

2
Alexey Romanov On BEST ANSWER

because in Mardin Odersky's book it has been written that A class and its companion object can access each other’s private members

This just means that you are allowed to access objA.a1 in the first snippet from object A, even though it isn't inside class A (and similarly, if you have any private members in object A, you can access them from class A). It isn't relevant to the second snippet at all.

Now my doubt is if I don't wanna use new operator to create an Object of A class how can A companion object will print a1(private variable) value and also access the A1 method of A class.

Well, you need to use new somewhere, because only instances of class A have A1() method and a1 field.

Note that the main special relationship between class A and object A is this special visibility rule (and other details are probably irrelevant to you at this stage of learning). So for A1() calls it doesn't at all matter that you have a companion object; it could equally be object B.

You can make object A an instance of class A by writing object A extends A, but this would just hide the new call in code generated by compiler.