Delegation controls the allocation of power/authority from an instance to another for any object. For classes and functions implementations, delegations can be used on static as well as mutable relations between them. Inheritance implementation in classes and functions can be altered with the help of delegation techniques and object-oriented programing languages support it innately without any boilerplate code. Delegation is used in Kotlin with the help of “by” keyword.
There are two types of delegation present in Kotlin:
• Explicit delegation: Supported by all object-oriented language and it is done by passing a delegate(the one to be implemented) object to delegating object (the one that will implement delegate object).
• Implicit delegation: Requires language-level support for the delegation pattern.
Let us discuss the concept of the delegation with the help of the examples:
As we know that in Kotlin, inheritance provides us with a permanent static relationship between objects which are not mutable while delegation is, this fact makes Delegation an extremely powerful alternative. In this example, using Newfeature class we can implement delegation base class with new features by delegating all its public members i.e mymessage and messageline and we are using this implementation with the help of “by” keyword.
GeeksforGeeks Welcome, GFG!
In this example, we have one delegation base class with val value and method “fun message()”. In the delegationimplementation class, we are assigning value to this “fun message” and later from another class we are using this implementation using “by” keyword to add a new statement with same val value;
delegationimplementation y = Hello!GFG GeeksforGeeks
1. It is a flexible, powerful as well as mutable method.
2. Multiple interfaces can be implemented with the help of the existing ones.
3. It is used to add new features and values to current implementations.
- Kotlin Data Types
- Hello World program in Kotlin
- Kotlin | Retrieve Collection Parts
- Destructuring Declarations in Kotlin
- DatePicker in Kotlin
- Kotlin labeled continue
- Introduction to Kotlin
- Kotlin Type Conversion
- Kotlin Exception Handling | try, catch, throw and finally
- Kotlin if-else expression
- Kotlin Environment setup for Command Line
- Kotlin constructor
- Kotlin Environment setup with Intellij IDEA
- Kotlin Nested class and Inner class
- Kotlin Variables
- Kotlin Operators
- Kotlin Standard Input/Output
- Kotlin Expression, Statement and Block
- Kotlin when expression
- Kotlin for loop
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.