Singleton And Companion Objects.

Singleton:

  • A singleton is a class that can have only one instance. In many cases we need a singleton object to stand for unique object in our software system. this is a singleton object:

            object MyObject { 
             val SomeField : Int = 5 
             def SomeMethod(name:String) : String = { "Hello, " + name }
            }
        
    

  • It is defined with the keyword object as oppose to class for a normal class.

  • There is no need to instainate it to use it : MyObject.SomeField

  • Objects are not evaluated until they are used, so the following is will compile but accessing DivByZero.BadField at runtime will give a error.

        object DivByZero {
         val BadField : Int = 5 / 0
        }
        DivByZero.BadField
         
    

  • It can inherit methods from other classes/traits.

        class BaseClass {
         def SomeMethod():String = "Cool!"
        }
        
        object SuperCool extends BaseClass {
         override def SomeMethod():String = "Super " + super.SomeMethod
        }
        
        val s = SuperCool
        def howCoolIsIt(arg:SuperCool.type) = arg.SomeMethod
        howCoolIsIt(s)
        
    

  • A singleton can be passed as a parameter.You can pass around variables that point to the singleton and you can use it as the argument and return type of a method

Companion Objects:

  • A singleton is said to be a companion object to a class when it has the same name with the class.

        class Vehicle(val vehicle_type : String)
        
        object Vehicle {
         var total_created = 0
         def countCars: Int = total_created 
         def apply(vehicle_type :String) : Vehicle= {
         total_created += 1
         new Vehicle(vehicle_type :String)
         }
        }
        
        val vehicle1= Vehicle("Sedan") //Calls the apply method and creates a new Vehicle instance
        val vehicle2 = Vehicle("Truck")
        val vehicle3 = Vehicle("Bus")
        Vehicle.total_created //Returns 3
        
    

  • The singleton (object) Vehicle, in this case, is called a companion object to the class Vehicle.

  • The attribute total_created is a static property and belongs to the singleton not an instance of the class vehicle.

  • Companion objects and classes have access to each other’s private fields

  • The companion and the class definition must both be in the same file.

  • Companion Objects are use to implement static method on a class where all static method for a class are put in the companion Object.

  • It's also worth noting that a singleton doesn't have to be a companion, it's perfectly valid to define a singleton without also defining a companion class as we have seen earlier.

PS: My First Blog post ever!!!. Always knew i will have to blog some day… just not when. Thanks to ikenna.consulting for the encouragement.