This post is going to be a short but sweet one as I introduce the power of Kotlin extensions!
Kotlin extensions allow you to simply extend the functionality of a given object. Say for some
reason you're developing an Android app and find yourself passing around an instance of context
a lot to get a simple desired result. As everyone (should) know, passing around an instance of
context
is dangerous. It can lead to memory leaks and makes your application more coupled,
complicating testing. Now, say I want to incorporate haptic feedback into my application where
every time a user clicks a button, the devices vibrates briefly. Normally, it may look something
like this:
class SomeSupportingClass {
fun vibrateOnTap(context: Context) {
val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator
vibrator ?: return
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(
VibrationEffect.createOneShot(HapticFeedbackConstants.KEYBOARD_TAP.toLong(), 1))
} else {
// Deprecated, but the replacement is only for 26+, so must use deprecated version
@Suppress("DEPRECATION")
vibrator.vibrate(HapticFeedbackConstants.KEYBOARD_TAP.toLong())
}
}
}
class SomeActivity : AppCompatActivity() {
// ... some functionality
val supportingClass = SomeSupportingClass()
fun doOnOkTapped() {
supportingClass.vibrateOnTap(this)
// implement logic ...
}
fun doOnMenuItemTapped() {
supportingClass.vibrateOnTap(this)
// implement logic ...
}
fun doOnSomethingTapped() {
supportingClass.vibrateOnTap(this)
// implement logic ...
}
}
fun Context.vibrateTap() {
val vibrator = this.getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator
vibrator ?: return
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(VibrationEffect.createOneShot(HapticFeedbackConstants.KEYBOARD_TAP.toLong(), 1))
} else {
// Deprecated, but the replacement is only for 26+, so must use deprecated version
@Suppress("DEPRECATION")
vibrator.vibrate(HapticFeedbackConstants.KEYBOARD_TAP.toLong())
}
}
class SomeActivity : AppCompatActivity() {
// ... some functionality
fun doOnOkTapped() {
vibrateTap()
// implement logic ...
}
fun doOnMenuItemTapped() {
vibrateTap()
// implement logic ...
}
fun doOnSomethingTapped() {
vibrateTap()
// implement logic ...
}
}
That's it! Nice, easy, and guaranteed to save time!