Scala – Companion Object
In the previous chapter, we have learnt about the Singleton Object. Now, let’s see study about companion object.
When you have a class with same name as singleton object, it is called companion class and the singleton object is called companion object. The companion class and its companion object both must be defined in the same source file.
Define nonstatic (instance) members in your class, and define members that you want to appear as “static” members in an object that has the same name as the class.
package main.testingpool
//Companion class
class Mobile {
var model = "Iphone" //Variable of companion class
def PhoneModel: Unit ={ //Method of companion class
println("Phone model : " + model)
}
}
object Mobile extends App{ //Companion Object
var obj = new Mobile()
obj.PhoneModel
}
Output - Phone model : Iphone