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.
This just means that you are allowed to access
objA.a1
in the first snippet fromobject A
, even though it isn't insideclass A
(and similarly, if you have any private members inobject A
, you can access them fromclass A
). It isn't relevant to the second snippet at all.Well, you need to use
new
somewhere, because only instances ofclass A
haveA1()
method anda1
field.Note that the main special relationship between
class A
andobject A
is this special visibility rule (and other details are probably irrelevant to you at this stage of learning). So forA1()
calls it doesn't at all matter that you have a companion object; it could equally beobject B
.You can make
object A
an instance ofclass A
by writingobject A extends A
, but this would just hide thenew
call in code generated by compiler.