Practical Extensions: Context, View & String Helpers
Build real Android-style utility extensions for common patterns.
Practical Extensions: Context, View & String Helpers is a free Kotlin Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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!")Context Resource Helpers
Avoid casting in resource lookups. Extensions improve readability and type safety.
import android.content.Context
import androidx.core.content.ContextCompat
fun Context.color(res: Int) = ContextCompat.getColor(this, res)
fun Context.string(res: Int) = getString(res)
fun Context.dp(value: Int) = (value * resources.displayMetrics.density).toInt()
// Usage: val red = context.color(R.color.error)View.show / View.hide
Toggle View.VISIBLE / View.GONE without ceremony.
import android.view.View
fun View.show() { visibility = View.VISIBLE }
fun View.hide() { visibility = View.GONE }
fun View.invisible() { visibility = View.INVISIBLE }
// Usage: progressBar.show(); button.hide()View.setVisible(boolean)
One-liner that toggles based on a condition — replaces if-else visibility code.
import android.view.View
fun View.setVisible(visible: Boolean) {
visibility = if (visible) View.VISIBLE else View.GONE
}
// Usage: errorLabel.setVisible(state.hasError)View.onClick Lambda
Cleaner click listener — passes a lambda instead of an anonymous OnClickListener.
import android.view.View
fun View.onClick(action: (View) -> Unit) {
setOnClickListener(action)
}
// Usage:
// button.onClick { view -> println("clicked") }String.isValidEmail
Domain-specific validation extensions on String make business logic readable.
fun String.isValidEmail(): Boolean {
val regex = Regex("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$")
return regex.matches(this)
}
fun main() {
println("ada@example.com".isValidEmail()) // true
println("nope".isValidEmail()) // false
}String.truncate
Truncate long strings with an ellipsis — common UI helper.
fun String.truncate(max: Int, ellipsis: String = "..."): String =
if (length <= max) this else substring(0, max - ellipsis.length) + ellipsis
fun main() {
println("The quick brown fox".truncate(10)) // The qui...
println("short".truncate(10)) // short
}String.toTitleCase
Capitalize each word — a common formatting helper.
fun String.toTitleCase(): String = split(" ").joinToString(" ") {
if (it.isEmpty()) it
else it[0].uppercaseChar() + it.substring(1).lowercase()
}
fun main() {
println("hello WORLD from kotlin".toTitleCase())
}List Extension: chunkedBy
Group consecutive elements by a key — useful for UI sections.
fun <T, K> List<T>.chunkedBy(keySelector: (T) -> K): List<List<T>> {
val result = mutableListOf<MutableList<T>>()
var lastKey: K? = null
for (item in this) {
val key = keySelector(item)
if (key == lastKey) result.last().add(item)
else { result.add(mutableListOf(item)); lastKey = key }
}
return result
}
fun main() {
val data = listOf(1, 1, 2, 2, 2, 3, 1)
println(data.chunkedBy { it }) // [[1, 1], [2, 2, 2], [3], [1]]
}Activity Helpers
Make navigation type-safe and shorter with reified generics.
import android.content.Context
import android.content.Intent
inline fun <reified T> Context.startActivity() {
startActivity(Intent(this, T::class.java))
}
// Usage: context.startActivity<MainActivity>()Don't Overdo It
Extensions add to the global namespace. Keep them focused, scoped (private/internal), and grouped by domain (one file per receiver type works well).
fun String.shout() = uppercase() + "!"
fun String.whisper() = lowercase() + "..."
fun main() {
println("hello".shout())
println("HELLO".whisper())
}Quick Check
Why are extensions a great fit for Android framework types like Context or View?
Recap
Extensions are perfect for adding ergonomic helpers to framework types (Context, View, String, List). Common patterns: visibility toggles, click listeners, resource lookups, validation, formatting. Keep extensions focused, scoped, and grouped by receiver type.
Frequently asked questions
Is the “Practical Extensions: Context, View & String Helpers” lesson free?
Yes — the full text of “Practical Extensions: Context, View & String Helpers” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.
What will I learn in “Practical Extensions: Context, View & String Helpers”?
Build real Android-style utility extensions for common patterns. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Kotlin Academy?
No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Practical Extensions: Context, View & String Helpers” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Kotlin Academy lesson?
Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
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