Practical Extensions: Context, View & String Helpers
Build real Android-style utility extensions for common patterns.
Real-World Extensions
Extensions shine on framework types you can't modify: Context, View, String, collections. Below are practical patterns straight from production Android codebases.
Context.toast Helper
Wrap the verbose Toast.makeText(...).show() in a one-liner extension.
import android.content.Context
import android.widget.Toast
fun Context.toast(message: String, long: Boolean = false) {
val duration = if (long) Toast.LENGTH_LONG else Toast.LENGTH_SHORT
Toast.makeText(this, message, duration).show()
}
// Usage: context.toast("Saved!")All lessons in this course
- Extension Functions: Syntax and Dispatch Rules
- Extension Properties and Computed Extensions
- Scoped Extensions and Companion Extensions
- Practical Extensions: Context, View & String Helpers