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.
var
and mutability is not the most idiomatic way to doing with Scala – cchantep