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:
- Any components that behave identically, but we realize were it will have some upgradation on top of it in future point of time where we do our own logical implementation and expose the results. For E.g. We can take an example of Analytics class, where instead of directly using the analytics method we can have our delegation and use the param to handle the screen views and event logging.
- Place where we feel delegate would be the better than inheritance because, it doesn’t force you to define all the methods of the super class, you can use or override only the methods that really needed. For e.g. here you can refer the code below that PaymentProcess doesn’t enforced to override the method (Kotlin), but if really needed we can override and do our implementations.
- If we want to extend the behavior of classes that we cannot or don’t want to subclass for the below reasons For E.g. here you can see in the below code snippet Payment classes (CashPayment, UPIPayment, CardPayment) are can’t be inherited.
- Restricted to share or disallowed to create a hierarchy (Class marked as final)
- Planning to expose the limited or different API methods by consuming the existing code functionality and also we may add our feature update.
- Planned to hide the serious implementation from the calling code.