Dealing with Method Collisions
Explore how Kotlin resolves method collisions in delegation scenarios by prioritizing the delegating class's methods. Understand how to override specific interface methods to avoid conflicts and implement robust delegation across multiple interfaces.
We'll cover the following...
Why collisions occur
The Kotlin compiler creates a wrapper in the delegating class for each method that’s in the delegate. What if there’s a method in the delegating class with the same name and signature as in the delegate? Kotlin resolves this conflict in favor of the delegating class. As a consequence, you can be selective and don’t have to delegate every single method of the delegate class—let’s explore this further.
In the previous example, the Worker has a takeVacation() method and the Manager is delegating calls to that method to the Worker delegate. Although that’s the default behavior for delegation in Kotlin, it’s unlikely that any Manager would settle for that; while it makes perfect sense for a Manager to delegate work(), one would expect the takeVacation() to be executed on the instance of Manager and not be delegated. ...