Kotlin extensions for Android — Part 1
These Kotlin functions do the same job as existing methods but provide simpler syntax.
Adding library
First of all, we add Google repository which is a publicly-available repository.
To add Google repository, add the following lines to your app module’s build.gradle:
repositories {
google()
}
In the same file, give instructions to the Gradle that we are going to use the library of Kotlin extensions:
dependencies {
// Check the latest version of this library here:
// https://github.com/android/android-ktx#getting-started implementation 'androidx.core:core-ktx:0.3'
}
Some of the cool extension functions are listed below:
1# Get System service
You can use this extension function to get System service (like AlarmManager
, DownloadManager
). For example:
val alarmManager = context.systemService<AlarmManager>()
2# Editing Shared Preferences
This gives you a simpler syntax if you want to perform operations on the Shared Preferences. For example:
val preferences = getSharedPreferences("MY_PREFERENCES", Context.MODE_PRIVATE)preferences.edit {
putBoolean("shouldAutoUpdate", false)
putString("nickname","John")
commit()
}
It should be noted that if you don’t specify commit()
, the apply()
will be used.
3# Creating a Bundle
This provides a simpler way to define a Bundle. For example:
val bundle = bundleOf(
"KEY_PRICE" to 50.0,
"KEY_IS_FROZEN" to false
)
In the above example, a Bundle object was created with two extras.
I have written about more extensions in this post:
Hope you liked this article!
Medium does not allow Indian writers to monetize currently 😭. Please support this blog by contributing here: https://www.patreon.com/malwinder 🥰
Even a small contribution would help 😍
If you have any questions, then please write down a response in the response section.
If you liked this article, then please press the 👏 icon.
Thank you!
Peace! 🙂