Passing Lambda Function for Adapter Callback in Kotlin

Pramono Winata
2 min readApr 5, 2019

--

Photo by JESHOOTS.COM on Unsplash

Kotlin has been a blast for the past 3 years. It has introduced Android programmer into the world of Functional Programming. There are a lot of magics that can be done with the power of Kotlin.

Today, I will introduce you the power of Lambda Function Kotlin that has never been seen in Java before!

Our daily lives Adapter

Remember that time when you are learning android and you need to implement click functionality on your adapter, which related to Activity(lets say navigation) and it needs the adapter object?

How do you do that? …

…..

….

..

Of course you created this pesky interface! with ONE method inside it

And then you set the interface as a callback inside your Adapter via constructor injection

Finally you implement it inside your Activity, while passing it into your adapter via constructor.

Whew! That whole process took 3 steps.

While it is not such a complicated process, that Interface always disturb me since the very first time i implemented those steps.

Interface with ONE method? Come on now, it is too Verbose.

Kotlin says NO to Verbosity

And here comes Kotlin into play.

Simply put, you can already forget that Interface.

There’s not much difference here, but in your Adapter class you pass in a Lambda Function inside, also via constructor.

Now, we will be going to our Activity class and it also doesn’t differ that much from before, only that it is injecting Lambda Function into the Adapter, via constructor.

And next step?

….

Wait, it is actually done!

Now your adapter click callback will work the same as the previous one, without that pesky Interface!

On a side note

It’s not that i hate Interface, in actuality i loved it! It’s in my opinion the greatest thing OOP has given to the world of Programming.

Lambda Function sure made things shorter, but it also a tradeoff to your readability, since it will make your code harder to be grasped by new engineers in your team.

All in all, getting to know how to use it would be the best, it will provide more alternatives and since it has been provided by the Programming Language itself, why not utilize it more then?

Thanks for reading, I hope you do enjoy it and hopefully it will be useful for you! Feel free to reach out for me if you have any feedback for me.

--

--

Responses (3)