Careeroza
Real World Example
Formatting Helpers in a Shopping App
Example
Indian apps format prices in rupees with the Indian grouping (1,23,456) and validate inputs. Extensions make call sites read like English.
fun Long.toRupees(): String {
val s = this.toString()
if (s.length <= 3) return "Rs $s"
val last3 = s.takeLast(3)
val rest = s.dropLast(3).reversed().chunked(2).joinToString(",").reversed()
return "Rs $rest,$last3"
}
fun String.isValidIndianMobile() = length == 10 && first() in '6'..'9' && all { it.isDigit() }
fun String.isValidPincode() = matches(Regex("[1-9][0-9]{5}"))
val Int.percentOff: String get() = "$this% OFF"
fun main() {
println(999L.toRupees())
println(123456L.toRupees())
println(12345678L.toRupees())
println("9876543210".isValidIndianMobile())
println("1234567890".isValidIndianMobile())
println("500032".isValidPincode())
println(40.percentOff)
}Output
Rs 999 Rs 1,23,456 Rs 1,23,45,678 true false true 40% OFF
Android View and Context Extensions
Almost every Android codebase has a small file of extensions like these (Android KTX from Google is a whole library of them).
fun View.show() { visibility = View.VISIBLE }
fun View.hide() { visibility = View.GONE }
fun Context.toast(message: String, long: Boolean = false) =
Toast.makeText(this, message, if (long) Toast.LENGTH_LONG else Toast.LENGTH_SHORT).show()
fun Fragment.hideKeyboard() {
val imm = requireContext().getSystemService<InputMethodManager>()
imm?.hideSoftInputFromWindow(requireView().windowToken, 0)
}
// Usage inside an Activity
binding.progressBar.show()
toast("Added to cart")