Thanks for you explanation!
It seams that the main purpose of class delegation in Kotlin was to overcome restriction of multiple inheritance in classes. Just like traits in PHP you can assemble target Kotlin class from pieces (i.e. various classes-delegates) using multiple inheritance of interfaces with "by" syntactyc shugar. So, instead of the following that won't compile
class Cat: FastMover(), Carnivoure() { ... }
we can make it working with class delegation feature
class Cat: CanMove by FastMover(), CanEat by Carnivoure() { ... }
Thanks for the explanation. It makes more sense to me now why delegation/composition it's better than inheriting or using abstract classes
However, from the example you gave, the delegation it's still a bit rigid. The cat should not enjoy the steak. It should have returned false.
I've seen an example where that is taken care of in the constructor (In this case, the Cat constructor) to make it much more flexible, but I was confused with the explanation.
I was hoping to get a better explanation here.
it was really helpful for me! thanks!
Thanks a lot!!🤗
Can somebody explain me with a more practical example what delegation is?
So it's multiple inheritance?
Yeah, basically multiple inheritance through composition with interfaces.
So what is the difference between class Cat: CanMove by FastMover() {...} and class Cat: FastMover {...}
The `by` keyword will use the classes interface definition for those interface definitions on the class. So your first example, Cat would use the FastMover implementation of CanMove while allowing you to implement other interfaces (using their own `by` keyword). Your second example would require FastMover to be `open` so it can be inherited from `Cat`, Kotlin only allows for inheriting from one parent class.
you don't wanna expose that your Cat is specifically a FastMover (as in, FastMover shouldn't be an exposed type)
Good video. However, you spelt Carnivore wrong. IntelliJ was saying you spelt it wrong.
Honestly...C# is more simple to implement delegate....
Thanks for such a good explanation and example. What I understood is:
Delegation allows having multiple implementations of an interface so then, the base class implementing that interface has to override the interface method. At this point it will be possible to make use of any of the implementations of the interface in the body of the overriden method of the base class and in Kotlin we can perform it from the class definition. Example:
class ClassI : InterfaceX by ClassAThatImplementInterfaceX()
class ClassJ : InterfaceX by ClassBThatImplementInterfaceX()
I wish it can help others to understand it easier (although the example in the video is perfectly clear) and not to bog down the path xD
Yup that's a great explanation and happy to hear this video helped you!