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. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, and your progress syncs across the web and the CoddyKit app. The Kotlin Academy course includes 4 lessons in total.
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.
Learn Kotlin with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 51
- Lessons
- 203
Frequently Asked Questions
Is the “Practical Extensions: Context, View & String Helpers” lesson free?
Yes — any 3 lessons of the Kotlin Academy learning path, including “Practical Extensions: Context, View & String Helpers”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Kotlin Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.
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