Using Kotlin extensions to make the Android SDK friendlier
Article Summary
The Android SDK's rough edges force developers into verbose workarounds. Kotlin extensions offer a cleaner path forward.
Colin White from Instacart breaks down how Kotlin extension functions improve Android SDK discoverability and developer experience. He shares practical extensions that simplify common pain points, building on concepts introduced in Google's Android KTX.
Key Takeaways
- Extension functions make APIs discoverable through autocomplete vs hidden util classes
- pxToDp and dpToPx extensions eliminate boilerplate for density conversions
- getColorCompat and getDrawableCompat alias AndroidX functions for easier discovery
- unsafeLazy skips thread locks for main-thread-only variables to boost performance
- inflate extension simplifies view inflation without parent attachment
Kotlin extensions transform clunky Android SDK patterns into fluent, discoverable APIs that autocomplete naturally in Android Studio.
About This Article
Android developers have to deal with API version fragmentation. Deprecated methods like resources.getDrawable() require conditional SDK_INT checks, and developers need to know about scattered compat utility classes like ResourcesCompat and AppCompatResources.
Colin White and Instacart used Kotlin extension functions to wrap AndroidX compat functions into fluent APIs. This lets Android Studio autocomplete discover them without needing version-specific implementation details.
Extensions like tint, toActivity, and openWebPage cut down boilerplate across all API levels. The unsafeLazy extension removes unnecessary thread-safe locks on main-thread variables. The result is cleaner code and better runtime performance.