Using extensions as properties
In the last recipe, we learned about extension functions. In this recipe, we will learn about extension properties. If you feel the need for one or more properties from the class, you can add them using the extension properties. In this recipe, we will learn how to use extension properties.
Getting ready
I'll be using Android Studio for coding purposes. Ensure that you have the latest version of Android Studio with Kotlin configured.
How to do it…
Let's see an example of an extension property now:
- We will be using the example of shared preferences. You might be used to doing something like this to get hold of shared preferences:
PreferenceManager.getDefaultSharedPreferences(this)
- You can create an extension property on theÂ
Context
class with name preferences and access it as follows:
valContext.preferences: SharedPreferences get() = PreferenceManager .getDefaultSharedPreferences(this) context.preferences.getInt("...")
How it works…
The extension functions...