I have seen few similar questions, but none had explained why delegation is limited to interfaces?
Most of the time in practice we have something that has actually no interface at all, it is a class that implements nothing but provides some functionality or implements an abstract class.
Is there any fundamental limitation that forces this to be limited to interfaces or can we expect kotlin to have unrestricted delegation in the future?
This is especially useful if we want to extend functionality of a class using composition not inheritance.
class A {}
class B(val a: A) : A by a {}
Advertisements. 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.
Interface delegation, in Kotlin, is a simple yet powerful technique that allows a class to delegate the actual implementation of the interfaces, to separate objects. NOTE: Kotlin interfaces support both abstract methods and abstract properties.
I'm an android developer and it's my pleasure to write in Kotlin because it takes my needs into account. Kotlin, unlike Java, supports delegation natively by language in the form of Class Delegation and Delegated Properties . Class Delegation feature uses Delegation pattern as an alternative to inheritance.
The primary advantage of delegation is run-time flexibility – the delegate can easily be changed at run-time. But unlike inheritance, delegation is not directly supported by most popular object-oriented languages, and it doesn't facilitate dynamic polymorphism.
When you delegate an interface, the class does still implement the interface. So for consistency, if you can delegate a class, it should work the same way. I.e.
class A(x: Int) {
fun foo() = x
}
class B(val a: A) : A by a {}
needs to compile to
class B(val a: A) : A {
override fun foo() = a.foo()
}
except this doesn't work:
foo
isn't open
and can't be overridden.
you need to call a constructor of A
. class B(val a: A) : A(a.x)
won't help either: x
is not a member of A
.
What about equals
and hashCode
: are they delegated? Either decision would lead to weird consequences.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With