Chapter 13. Extensions

Sometimes the functionality provided by Android and iOS just isn’t enough, and sometimes the functionality provided by third-party libraries or internal objects just doesn’t make the cut. Sure, you can subclass, but it’s not always feasible for that to work properly.

Fortunately, both platforms have a means to augment existing objects.

Tasks

In this chapter, you’ll learn to add functionality to existing APIs.

Android

While we have spent the majority of this book defaulting to Java as the language for Android development, and indeed the great majority of Android development does happen in Java, we must now mention that in the Android Framework, only Kotlin is capable of supporting extensions. What does that mean? Let’s define the word “extension” to mean “alter or add functionality to any class.” However, Java classes in a project with Kotlin extensions can take advantage of the extended functionality!

Add Functionality to Existing APIs

In Java, if you import a third-party library for CalendarPicker, you’re pretty much stuck with whatever public API that library provides. Of course, you can alter the source, but at that point you’ve created your own CalendarPicker, which will not be an instance of the same class as the original. You could also subclass CalendarPicker, but the same caveat applies. It is not possible to add or change the existing functionality of the existing CalendarPicker API.

In Kotlin, this is no longer true. Not only could you add ...

Get Native Mobile Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.