Extension Functions You Need to Know in Android
Leveraging the Power of Kotlin
Kotlin brings in many incredible features. Among the many different types of functions, we have Extension functions. They are compiled into regular Java functions in the back; however, it makes the coding interface look a lot cleaner.
#0 — Toast message
This is the simplest extension function and every article would tell you to have this.
You can now use this function in your Activity or Fragment to display a toast more easily.
#1 — Repeating a string
Another very common operator
extension function that not many people would know about.
Now that we have the two common ones out of the way, let’s get into some interesting ones.
#2 — String substring
I am sure you are aware of retrieving a character from a string using str[index]
. Now, what if you require a substring but hate to type out that long function name?
I overloaded the get
operator function with an IntRange parameter which would return the substring within the required index range.
#3 — Android resources
If you need any resources in your Kotlin code, it is a simple function away. Remove your boilerplate code and instead call your Extension function for cleaner code. For debugging purposes, use a suitable Annotation so that you are alert if you pass the wrong resource type.
#4 — Complex units
You need to set the font size, or box width programmatically but in terms of dp
and sp
? In Java, you’d rather use a function; however, in Kotlin, you can create an Extension value.
Conclusion
Every Android developer loves Kotlin and it only makes sense if we use it to its full potential. Kotlin is an ever-growing language and with every update, it is only getting better.