In the previous chapter, you saw that Kotlin offers a different and safer way to use inheritance than Java. Likewise, Kotlin has much better support than Java for delegation. Before we dive into the syntax for delegation, we’ll take a small problem and design it using inheritance, to better understand the reasons to use delegation over inheritance. Soon we’ll run into issues where inheritance begins to become a hindrance, and you’ll see how delegation may be a better choice for the problem. We’ll then look at how Kotlin is able to readily support our new design using delegation, without flinching.

A design problem

Imagine an application that simulates the execution of software projects by corporate teams (don’t worry, we’ll limit the scope so our program, unlike some enterprise projects, actually completes). We need workers to get real stuff done—let’s start with a Worker interface:

// version1/project.kts
interface Worker {
  fun work()
  fun takeVacation()
}

A worker may perform two tasks: does work and occasionally takes vacation. Let’s implement two classes, JavaProgrammer and CSharpProgrammer, that specialize in two different languages—the idea of being polyglot has not caught this company’s attention yet.

Get hands-on with 1400+ tech skills courses.