Delegating to a Parameter

We'll cover the following

The problem

In the previous example, we wrote Worker by JavaProgrammer(), which says that the Manager instance is delegating to an implicitly created instance of the JavaProgrammer, but that poses two issues. First, the instances of Manager class can only route to instances of JavaProgrammer, not to instances of any other Worker implementors. Second, an instance of Manager doesn’t have access to the delegate; that is, if we were to write a method in the Manager class, we can’t access the delegate from that method.

The solution

It’s easy to fix those limitations by tying the delegate to the parameter passed to the constructor instead of to an implicitly created instance.

// version5/project.kt
class Manager(val staff: Worker) : Worker by staff {
  fun meeting() =
    println("organizing meeting with ${staff.javaClass.simpleName}")
}

The constructor of the Manager class receives a parameter named staff which also serves as a property, due to val in the declaration. If the val is removed, staff will still be a parameter, but not a property of the class. Irrespective of whether or not val is used, the class can delegate to the parameter staff.

In the meeting() method of the Manager class, we’re able to access staff since it’s a property of the object. Calls to methods like work() will go to staff due to delegation. Let’s confirm this behavior by creating a couple of instances of this version of Manager.

Get hands-on with 1200+ tech skills courses.