IDAP BLOG Code

Android arguments with Kotlin delegates

In Android, Bundle is used for sending data between Activities and Fragments.

For example, to pass userName in Activity, we use Intent:

In a Fragment we can use Bundle directly:

The following code allows us  to extract passed argument in a fragment:

In the same line we have to write userName twice, and this is too much in Kotlin world.

What about the following variant:

How we can implement it in Kotlin?

It can be done with delegated properties that allow us to implement our own getters/setters.

Firstly, let’s implement argumentDelegate() for a certain type parameter, for example  a String. We can represent our delegate for Fragment as follows:

This function returns an anonymous object that implements ReadOnlyProperty interface. This fact allows us to use this function together with Kotlin ‘by’ keyword in our fragment. Okay, well done, but what about all variety of types that could be passed to Bundle?

Of course, we need generic version of our delegate. Using reified type parameter, it’s pretty easy to do:

Since we also use it in Activity, we cannot focus on Fragment::arguments only. We could write an extension for Activity in the same way, but it would lead to code duplication and this is not that we had actually wanted. It doesn’t matter if you use Activity or Fragment, at the end data is saved in Bundle. So, we can extract a piece of code that works directly with arguments into a separate function.

Now we can easily create an Activity extension for the same purpose:

One more thing. In that case, each time, when you accessing to the userName, bundle::get will be called. That we need to improve is a fact that it would be great to use some kind of caching if we use extracted variables many times. For this case Kotlin has another nice feature – Lazy. So let’s try with it:

And as the last tiny edit, we have to do something in edge cases, like when no arguments were passed.

All the code written above is available at ArgumentDelegate library. Looking forward to getting your feedback.

(26 votes, average: 4.81 out of 5)
Loading...