Real World Example

Reusable Helpers in an App

Real apps have small, well-named functions for things used on many screens: formatting prices, validating input, calculating fees. Default and named arguments keep the call sites short and clear. These are typical helpers from a food delivery or e-commerce Android app.

Example

Price formatting, validation and fee calculation:

fun formatRupees(paise: Long, showPaise: Boolean = true): String {
    val rupees = paise / 100
    val rest = (paise % 100).toString().padStart(2, '0')
    return if (showPaise) "₹$rupees.$rest" else "₹$rupees"
}

fun isValidPhone(phone: String) = phone.length == 10 && phone.first() in '6'..'9' && phone.all { it.isDigit() }

fun deliveryFee(distanceKm: Double, isPrime: Boolean = false, isRaining: Boolean = false): Int {
    if (isPrime) return 0
    val base = when {
        distanceKm <= 3 -> 25
        distanceKm <= 7 -> 45
        else -> 70
    }
    return if (isRaining) base + 20 else base
}

fun main() {
    println(formatRupees(54_905))
    println(formatRupees(54_905, showPaise = false))
    println(isValidPhone("9876543210"))
    println(isValidPhone("1234567890"))
    println(deliveryFee(2.5))
    println(deliveryFee(5.0, isRaining = true))
    println(deliveryFee(9.0, isPrime = true))
}

Output

₹549.05
₹549
true
false
25
65
0

Practice

Exercise: Write fun bmi(weightKg: Double, heightM: Double): Double as a single-expression function, and fun bmiCategory(bmi: Double): String that returns "Underweight" (< 18.5), "Normal" (< 25), "Overweight" (< 30) or "Obese".

Show answer
fun bmi(weightKg: Double, heightM: Double) = weightKg / (heightM * heightM)

fun bmiCategory(bmi: Double) = when {
    bmi < 18.5 -> "Underweight"
    bmi < 25 -> "Normal"
    bmi < 30 -> "Overweight"
    else -> "Obese"
}

fun main() {
    val value = bmi(68.0, 1.72)
    println("%.1f".format(value))   // 23.0
    println(bmiCategory(value))     // Normal
}