Android: RecyclerView Adapters with Kotlin

Moksh Jain
2 min readJul 13, 2017

Introduction

At Google I/O 2017, Kotlin was added as an official programming language for Android. Though support for Kotlin was present previously (through an Android Studio plugin), being an officially supported language motivates a wider community to adopt Kotlin for Android Development.

Even though Kotlin is being used as a language for Android Development for a couple of years, the number of Kotlin-specific Android documentation and examples is surprisingly low. Ideally this shouldn’t be a problem since Kotlin is fully inter-operable with Java, as it runs on JVM, so you can very easily translate Java code to Kotlin by simple copying it and Android Studio does the translation for you. But Kotlin has a lot of subtle tricks up it’s sleeves, which can drastically reduce the amount of code you write.

Recently, while working on an application, I had to implement a RecylerView Adapter in Kotlin. Being quite new to Kotlin, I struggled to get one working. So after struggling for a while, referring to some examples online and tinkering with the code, I managed to find a solution.

The Code

Let us start by looking at an implementation of a RecyclerView Adapter in Java with onClick support.

Now, before we move on to the Kotlin implementation, let me explain in brief what our code here does.

  • The constructor initialises the Adapter object with a list of ViewItems which hold the data to be displayed in the RecyclerView items.
  • The onCreateViewHolder method is responsible for inflating the item layout in the parent view i.e. the RecyclerView
  • The onBindViewHolder is essentially where you display the content on the view item.
  • getItemCount is essentially a method that tells the RecyclerView how many items are to be inflated.
  • The ClickListener interface is essentially what provides onClick functionality to the RecyclerView item. The reason for using a seperate interface for this is that it provides a lot of flexibility, allowing you to define different onClick actions for different usages of the adapter.
  • And finally, the ViewHolder class is essentially the View Item, where you define it’s children, etc and most importantly set the clickListener.

Now, we look at the Kotlin implementation.

The Kotlin implementation is largely void of a lot of the boilerplate in the Java implementation of the same adapter. The code is much easier to maintain without all the boilerplate to worry about.

The adapter can then be declared as follows:

val adapter = ViewAdapter(list) {
// do stuff onClick
}

--

--