Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the responsive-lightbox domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114

Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the hueman domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114
Scala - Companion Object - Testingpool

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
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...