Part 05 / Stage 1
Functions
Goal: Declare functions with typed parameters and return values, use single-expression bodies where they fit, understand
Unit, make a function flexible with default and named arguments, accept a variable number of arguments withvararg, keep a helper private with a local function, and let the same function name mean different things through overloading. Time: ~5 hours · Level: comfortable with control flow (Part 4)
What you will learn
- Declaring a function: parameters with explicit types, a return type, and how top-level
functions sit alongside
main()in the very same file - Single-expression functions, and when Kotlin lets you drop the return type versus when it insists on one
Unit: Kotlin's "this function returns nothing meaningful" type, and why it is a real type with a real value, not Java'svoid- Default arguments (a parameter that supplies its own value when the caller skips it) and named arguments (calling by parameter name instead of position)
vararg: accepting a variable number of arguments of the same type, and the spread operator (*) for handing it an existing array- Local functions: a helper function declared inside another function, visible only there
- Basic overloading: more than one function sharing a name, told apart by their parameter lists
- Building a discount calculator that totals a bill, applies a membership discount, a coupon and GST, using every tool above
Topics in this part
Practice
Try each one yourself first. Then check the solution.
Every exercise is one file with a top-level fun main(), using only what Parts 1–5 have covered
so far: val/var, basic types, null safety, control flow, and this part's functions. No
collections beyond listOf/mutableListOf, no classes, no lambdas or higher-order functions --
those come in later parts.
Exercise 1: Auto fare function
Scenario: Part 4's auto-rickshaw fare slabs (0–5 km ₹20, 6–15 km ₹35, 16–30 km ₹60, else ₹100),
now as a reusable function instead of inline code.
What to do: write a block-body function fun fareFor(km: Int): Int with an explicit return
type, using the same slabs as a when. Call it from main() for distances 3, 12, 25 and
40, printing "$km km -> ₹$fare" for each.
Sample output:
3 km -> ₹20
12 km -> ₹35
25 km -> ₹60
40 km -> ₹100
💡 Hint: this is exactly Part 4's when logic, just wrapped in a function with a return
inside each branch, or returned once from a val computed by the when.
Exercise 2: GST, as a single expression
Scenario: a Jaipur handicrafts shop wants a quick GST calculator for its till.
What to do: write a single-expression function fun priceWithGst(amount: Double): Double
that adds 18% GST to amount. Call it for 500.0, 1250.0 and 99.0, printing
"₹%.2f incl. GST: ₹%.2f".format(amount, priceWithGst(amount)) for each.
Sample output:
₹500.00 incl. GST: ₹590.00
₹1250.00 incl. GST: ₹1475.00
₹99.00 incl. GST: ₹116.82
💡 Hint: amount * 1.18 is the whole function body -- no braces, no return, just =.
Exercise 3: Birthday greeting with a default argument
Scenario: a greeting-card app in Kochi sends the same message for most occasions, but a few
customers pick a custom line.
What to do: write fun greetingFor(name: String, occasion: String = "a wonderful day"): String
returning "Dear $name, wishing you $occasion!". Call it three times: once with just a name, once
naming occasion explicitly, and once passing both positionally.
Sample output:
Dear Asha, wishing you a wonderful day!
Dear Rohan, wishing you a joyous Diwali!
Dear Meera, wishing you a happy anniversary!
💡 Hint: the default only kicks in when the caller leaves occasion out entirely -- passing it
by name or by position both override it the same way.
Exercise 4: Vararg bill total
Scenario: a Nagpur kirana store wants to total up any number of item prices in one call, plus
total a basket collected into a list at runtime.
What to do: write fun billTotal(vararg amounts: Double): Double that sums its arguments.
Call it directly with three literal amounts, then build a val basket = mutableListOf(45.0, 120.0, 75.50, 30.0), convert it to a DoubleArray with .toDoubleArray(), and call billTotal again
using the spread operator on that array.
Sample output:
Three items: ₹265.00
Basket of 4: ₹270.50
💡 Hint: billTotal(*basket.toDoubleArray()) -- the * is required; handing the array over
without it is a type error, since billTotal expects individual Double arguments, not one
DoubleArray value.
Exercise 5: Local function for recharge validation
Scenario: a prepaid recharge kiosk in Indore only accepts recharge amounts from ₹10 to ₹5000.
What to do: write fun processRecharge(amount: Double): String that declares a local
function isValidAmount(a: Double) = a in 10.0..5000.0 inside it, uses that local function to
decide the message, and returns "Recharge of ₹%.2f successful".format(amount) when valid or
"Recharge of ₹%.2f rejected: out of range".format(amount) otherwise. Call it for 200.0,
5.0 and 7500.0.
Sample output:
Recharge of ₹200.00 successful
Recharge of ₹5.00 rejected: out of range
Recharge of ₹7500.00 rejected: out of range
💡 Hint: isValidAmount only matters inside processRecharge -- that is exactly why it
belongs as a local function instead of a second top-level function nobody else will ever call.
Exercise 6: Overloaded shipping cost
Scenario: a Surat courier service prices a shipment either by weight or by distance, and both
callers just say shippingCost(...).
What to do: write two overloaded functions: fun shippingCost(weightKg: Double): Double
returning weightKg * 40.0, and fun shippingCost(distanceKm: Int): Double returning
distanceKm * 8.0. Call shippingCost(2.5) and shippingCost(150) from main(), printing which
overload's result came back and the value, e.g. "By weight (2.5 kg): ₹100.00".
Sample output:
By weight (2.5 kg): ₹100.00
By distance (150 km): ₹1200.00
💡 Hint: 2.5 is a Double literal and 150 is an Int literal -- the compiler picks the
matching overload from each argument's own static type, with no runtime check involved at all.
Exercise 7: Loyalty checkout, end to end
Scenario: a smaller cousin of this part's discount calculator, for a Vadodara stationery shop -- one item at a time, a loyalty-years membership, and GST, run interactively. What to do: write a program that:
- Reads one item price with
readlnOrNull()?.trim()?.toDoubleOrNull() ?: 0.0. - Reads loyalty years the same way, as an
Int(?: 0). - Computes a membership discount percent with a function
fun loyaltyDiscountPercent(years: Int): Double--0years →0.0,1–2years →5.0,3years or more →12.0-- returned via awhen. - Computes the final price with
fun finalPrice(amount: Double, discountPercent: Double = 0.0, gstPercent: Double = 18.0): Double, called with named arguments, applying the discount first and then GST on what's left. - Prints
"Discount: X.X%"then"Final price: ₹Y.YY".
Sample output: (piped input: price 800, then 4 years)
$ kotlinc ex07.kt -include-runtime -d ex07.jar
$ printf '800\n4\n' | java -jar ex07.jar
Enter item price: ₹Enter loyalty years:
Discount: 12.0%
Final price: ₹830.72
Sample output: (a brand-new customer, 0 years)
$ printf '450\n0\n' | java -jar ex07.jar
Enter item price: ₹Enter loyalty years:
Discount: 0.0%
Final price: ₹531.00
💡 Hint: 800 - 800 * 0.12 = 704, then 704 * 1.18 = 830.72 -- discount comes off first, GST
goes on top of what's left, same order the Part 5 capstone uses.
Show the solutions for Part 5 (7 files)
solutions/ex01.kt
fun fareFor(km: Int): Int {
return when (km) {
in 0..5 -> 20
in 6..15 -> 35
in 16..30 -> 60
else -> 100
}
}
fun main() {
for (km in listOf(3, 12, 25, 40)) {
println("$km km -> ₹${fareFor(km)}")
}
}
solutions/ex02.kt
fun priceWithGst(amount: Double): Double = amount * 1.18
fun main() {
for (amount in listOf(500.0, 1250.0, 99.0)) {
println("₹%.2f incl. GST: ₹%.2f".format(amount, priceWithGst(amount)))
}
}
solutions/ex03.kt
fun greetingFor(name: String, occasion: String = "a wonderful day"): String {
return "Dear $name, wishing you $occasion!"
}
fun main() {
println(greetingFor("Asha"))
println(greetingFor("Rohan", occasion = "a joyous Diwali"))
println(greetingFor("Meera", "a happy anniversary"))
}
solutions/ex04.kt
fun billTotal(vararg amounts: Double): Double {
var total = 0.0
for (a in amounts) total += a
return total
}
fun main() {
println("Three items: ₹%.2f".format(billTotal(100.0, 90.0, 75.0)))
val basket = mutableListOf(45.0, 120.0, 75.50, 30.0)
println("Basket of 4: ₹%.2f".format(billTotal(*basket.toDoubleArray())))
}
solutions/ex05.kt
fun processRecharge(amount: Double): String {
fun isValidAmount(a: Double) = a in 10.0..5000.0
return if (isValidAmount(amount)) {
"Recharge of ₹%.2f successful".format(amount)
} else {
"Recharge of ₹%.2f rejected: out of range".format(amount)
}
}
fun main() {
println(processRecharge(200.0))
println(processRecharge(5.0))
println(processRecharge(7500.0))
}
solutions/ex06.kt
fun shippingCost(weightKg: Double): Double = weightKg * 40.0
fun shippingCost(distanceKm: Int): Double = distanceKm * 8.0
fun main() {
val byWeight = shippingCost(2.5)
println("By weight (2.5 kg): ₹%.2f".format(byWeight))
val byDistance = shippingCost(150)
println("By distance (150 km): ₹%.2f".format(byDistance))
}
solutions/ex07.kt
fun loyaltyDiscountPercent(years: Int): Double = when {
years >= 3 -> 12.0
years >= 1 -> 5.0
else -> 0.0
}
fun finalPrice(amount: Double, discountPercent: Double = 0.0, gstPercent: Double = 18.0): Double {
val afterDiscount = amount - amount * discountPercent / 100
return afterDiscount + afterDiscount * gstPercent / 100
}
fun main() {
print("Enter item price: ₹")
val price = readlnOrNull()?.trim()?.toDoubleOrNull() ?: 0.0
print("Enter loyalty years: ")
val years = readlnOrNull()?.trim()?.toIntOrNull() ?: 0
val discountPercent = loyaltyDiscountPercent(years)
val total = finalPrice(price, discountPercent = discountPercent)
println()
println("Discount: %.1f%%".format(discountPercent))
println("Final price: ₹%.2f".format(total))
}
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Leaving a parameter's type off (fun add(a, b): Int) |
Kotlin never infers a parameter's type from the call site, only a function's return type, and only in limited cases | Give every parameter an explicit type |
Dropping the return type from a block-body function that returns something other than Unit |
The compiler assumes Unit the moment it's missing, then reports a type mismatch at every return |
Add the real return type after : |
Writing : Unit on every function with nothing to return |
Legal, but adds visual noise Unit-by-omission already covers |
Omit the return type entirely for a Unit-returning function |
| Treating a default argument as "always optional, any order" | A default lets you skip a parameter, but skipping one in the middle still needs the rest named | Either supply every earlier parameter positionally, or switch to named arguments |
Putting more than one vararg parameter in a function |
Kotlin allows exactly one vararg parameter per function |
Combine the values into a single array/vararg, or accept a List instead |
Passing an existing array where a vararg is expected, without * |
A vararg parameter expects individual arguments, not one array value |
Spread it: fn(*myArray) |
| Expecting a local function to be visible outside its enclosing function | Local functions are scoped to the function that declares them, same as a val declared inside a block |
Promote it to a top-level function once more than one place needs it |
| Assuming overloads differing only by a defaulted parameter are always ambiguous | They're ambiguous only when two or more candidates would need a default filled for the same call; an exact-arity match always wins first | Test the actual call -- or add enough arguments that only one candidate fits |
Quick recap
- A function needs an explicit type on every parameter; its return type can often be inferred, but a block body returning non-
Unitmust state it. - A single-expression function skips braces and
return; a block body needs both, and is the only shape multiplereturnpoints fit in. Unitis a real type with one value, used (explicitly or, idiomatically, by omission) whenever a function has nothing meaningful to return.- Default arguments supply a fallback value; named arguments let a call skip around defaults, or simply read more clearly, regardless of parameter order.
varargaccepts a variable number of same-typed arguments;*arrayspreads an existing array into that same vararg position.- A local function is scoped to the function that declares it, and can read and change that function's own
vars. - Overloading tells functions apart by their parameter list, resolved at compile time from the static types of the arguments at each call site.
Checklist
- I declared a top-level function with typed parameters and an explicit return type, called it from
main(), and (optionally) confirmed withjavapthat it compiles alongsidemainin the same class. - I wrote a single-expression function, and separately caused and read the real compiler error from dropping a block-body function's return type.
- I can explain why
Unitis a type with a value, not Java'svoid. - I called the same function three ways: all defaults, one positional override, and named arguments supplied out of order.
- I wrote a
varargfunction and called it both with individual arguments and with*spreading an existing array. - I wrote a local function that reads and changes a
varfrom its enclosing function. - I wrote two overloaded functions and traced, for each call, which one the compiler picked and why.
- I built and ran the discount calculator myself, including a run that uses the loyalty-years overload and one with an invalid price.