Using Kotlin to Make the PSPDFKit API Even Better

Share

Here at PSPDFKit, we take great care that our APIs are easy to use, while still providing the necessary flexibility and extendibility for you to achieve what you want. But even with all the care taken, there are still areas that could be better. So what if I told you there was a way for you to improve upon our APIs yourself?

Kotlin Extension Functions

Kotlin provides the ability to extend any class with new functionality via what’s known as extension functions. You can think of them as a fancy way to define static utility methods.

As you can see, we can call our extension function just like we would any other method on the object. We aren’t going to go into all the details about extension functions here, but for more information you can check out the official documentation.

Example

To illustrate this idea, let’s look at one general example of how an extension function can improve your code.

Let’s say you want to show a Toast in your activity. Normally, it would look like the following:

As shown above, using an extension function greatly simplified the code. We made the duration an optional parameter, since we use the same duration for most cases. We also moved the call to show() inside our extension function, so you no longer need to wonder why your Toastwas never displayed.

How To Improve the PSPDFKit API

While developing PDF Viewer, we came up with a few extension functions that make using PSPDFKit even simpler. These range from basic (making properties easier to access) to complicated (turning a long-running synchronous task into something async). Let’s look at some examples right now.

Examples

In many places, we had to modify an existing PdfActivityConfiguration, so we came up with this simple extension function to help out:

// Get the needed size for our preview image.valtargetSize=document.getPageSize(0).fitInside(width.toFloat(),height.toFloat())

Wrapping Things Up

Kotlin’s extension functions are incredibly powerful and can help make your code much more concise and clear. However, keep in mind that not everything should be an extension function, and there are still situations where a regular utility method makes more sense.

You can find all the extension functions I talked about (and more) included in PSPDFKit for Android, beginning with version 4.3.1. — you can check them out in the Catalog App that we provide with the 60-day trial of PSPDFKit for Android.