Sunday, 12 June 2022

Kotlin Delegation

In object-oriented programming, delegation refers to evaluating a member (property or method) of one object (the receiver) in the context of another original object (the sender). 


Delegation is a design pattern in which an object handles a request by delegating to a helper object, called the delegate. The delegate is responsible for handling the request on behalf of the original object and making the results available to the original object.  


Kotlin supports “delegation” design pattern by introducing a new keyword “by”. Using this keyword or delegation methodology, Kotlin allows the derived class to access all the implemented public methods of an interface through a specific object


Delegation should be used when:

  • When your subclass violates the Liskov substitution principle.  For example, when we are dealing with situations where inheritance was implemented only to reuse code of the superclass, but it is not really acting like it.
  • When the subclass uses only a portion of the methods of the superclass. In this case, it is only a matter of time before someone calls a superclass method that they were not supposed to call. Using delegation, we reuse only methods we choose (defined in the interface).
  • When we cannot or we should not inherit, because:
    • The class is final
    • It is not accessible and used from behind interface
    • It is just not designed for inheritance

Example: This will be very simple and self-explanatory code snippet, here we are having an interface IPayment for the payment and it would track the mode of payment happens, and there would be an implementation classes CashPayment, UPIPayment, CardPayment of different mode of payment (Cash, Card and UPI).   There in PaymentProcess class the delegation will be happen through the interface.  Also the method paymentProcess in java and processPayment in Kotlin does the payment process.   

Comparatively with Java and Kotlin, In Kotlin we avoid lot of boilerplate code because of delegation using “by”, else in java we are mandatory to do the implementation of all interface method (see in this example I have used only one interface method, so if it is more than, it would be more override method in PaymentProcess.java class). 


Java Style of Delegate


Kotlin Style of Delegate:

Happy Coding :-)

No comments: