Extending Android framework using extension function
The heading of this recipe might seem very confusing to you as you might be thinking "How can I extend the super complex Android framework? And moreover, why should I?" We will be dealing with all the "what, why, and hows" of extension functions in this recipe. Extension functions are one of the greatest features of Kotlin. So let's dive into it.
Getting ready
I'll be using Android Studio for coding. We will be creating extension functions for Android SDK classes.
How to do it…
To begin with, let's see a very simple example:
- We will create a very simple class
Student
, and we will create an extension function for it:
class Student(val age:Int)
- Now, we would want to create an
isAgeGreaterThan20
function, which will returntrue
if the age is greater than 20, or else, will returnfalse
. Now suppose there's a restriction that we can't touch the Student class, what will you do? - In those scenarios, extension functions come in handy when you want to...