Welcome to our in-depth guide on Kotlin Class Delegation using the by keyword! This tutorial is designed for beginners and intermediates, so let's dive right in. 🎯
Class Delegation in Kotlin is a way to implement an interface by using another class as a delegate. This is particularly useful when we want to reuse an existing class that already implements some functionality required by an interface. 💡
To use Class Delegation, we'll be using the by keyword followed by the delegate class. Here's a simple example:
interface Printable {
fun print()
}
class PrintDelegate : Printable {
override fun print() {
println("Hello, World!")
}
}
class DelegatedPrintable(delegate: Printable) : Printable by delegate
fun main() {
val printable = DelegatedPrintable(PrintDelegate())
printable.print() // Output: Hello, World!
}In this example, Printable is an interface, and PrintDelegate is a class that implements Printable. We create a new class DelegatedPrintable that delegates its Printable interface implementation to the provided delegate (PrintDelegate in this case).
Class Delegation can be used with multiple interfaces as well. Let's extend our example:
interface Printable {
fun print()
}
interface Readable {
fun read()
}
class PrintDelegate : Printable {
override fun print() {
println("Hello, World!")
}
}
class ReadableDelegate : Readable {
override fun read() {
println("Reading from delegate")
}
}
class DelegatedPrinter(val printDelegate: Printable, val readDelegate: Readable) : Printable by printDelegate, Readable by readDelegate
fun main() {
val printable = DelegatedPrinter(PrintDelegate(), ReadableDelegate())
printable.print() // Output: Hello, World!
printable.read() // Output: Reading from delegate
}In this example, we have two interfaces (Printable and Readable) and two delegates (PrintDelegate and ReadableDelegate). The DelegatedPrinter class delegates both Printable and Readable interfaces to their respective delegates.
In the example provided, which class delegates the Printable and Readable interfaces to their respective delegates?
That's it for our Kotlin Class Delegation tutorial! We hope you found this guide helpful in understanding and implementing Class Delegation in your projects. Happy coding! ✅