Book Image

Programming Kotlin

Book Image

Programming Kotlin

Overview of this book

Quickly learn the fundamentals of the Kotlin language and see it in action on the web. Easy to follow and covering the full set of programming features, this book will get you fluent in Kotlin for Android.
Table of Contents (20 chapters)
Programming Kotlin
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

Class delegation


You might have already heard about the delegation pattern or at least used it without even knowing it had a name. It allows a type to forward one or more of its methods call to a different type. Therefore, you need two types to achieve this: the delegate and the delegator.

This could easily sound like a proxy pattern, but it isn't. A proxy pattern is meant to provide a placeholder for an instance to get full control while accessing it. Let's say you are writing a UI framework and you start where your abstraction is UIElement. Each of the components define a getHeight and getWidth.

Class delegation via association

Below you see the UML translated into Kotlin. We defined the UIElement interface with both Panel and Rectangle classes inheriting from:

    interface UIElement { 
      fun getHeight(): Int 
      fun getWidth(): Int 
    } 
    class Rectangle(val x1: Int, val x2: Int, val y1: Int, val y2: Int) : UIElement { 
      override fun getHeight...