This is just one more example about how in Kotlin we can continue to use the same libraries we’ve always used in Java for Android.

Retrofit is a library that greatly simplifies doing requests to an API, and in this case I’m going to teach you how to integrate it with some LastFM API requests. You can see the full code working in the Bandhook Kotlin repository.

Retrofit 2 in Kotlin

The code in Kotlin is going to be very similar to what we would use in Java. We’ll see more in detail what are some of their differences, but you’ll see that everything is pretty easy and intuitive.

And we’ll also create some very useful extension functions, you’ll see.

Build the build.gradle

I won’t stop here too much, but you need to add the following instructions to build.gradle:

The first dependencies include the latest version of OkHttp and a logging interceptor, which can be useful for debugging.

The following add Retrofit (excluding OkHttp, so we have control over the version we use), and the Gson converter to convert requests to classes.

Create the communication interface

This is the neuralgic part of Retrofit. It’s where you specify the structure of the requests, which will have to match the API:

It’s quite simple. It identifies the type of the request with the notation, and then the parameters of the request as arguments of the function.

In Retrofit 2, we need to return objects of type Call.

Initialization of the communication service

First you can initialize the OkHttp client as follows:

Here we can see the use of the function, apply, which will help us initialize the interceptor in the style of a builder, without the need for the class to implement any type of builder.

The LastFmRequestInterceptor has nothing remarkable, but you can take a look on Github. The creation of the service has nothing different to Java:

Make your first request

Due to the need for Call in Retrofit 2, it becomes a bit more tedious code:

However, thanks to the extension functions, we can create a function on Call to retrieve the values, like this:

Much simpler, right?

What is the form of unwrapCall?

It’s a function that extends Call class. It will execute the request, retrieve the body, and make this one (which will be of type U) execute the function f().

In the above example T is LastFmResponse and U is List.


With this example I wanted to show you once again that any of the Java libraries you know and love can be used in Kotlin without issues.

Also, far from making things more complicated, in most cases the language will simplify the code.

Get ready and take a look at the free guide to learn how to build your first project, or just get the book and learn how to create a complete App from scratch.

Author: Antonio Leiva

I’m in love with Kotlin. I’ve been learning about it for a couple of years, applying it to Android and digesting all this knowledge so that you can learn it with no effort.