Functions package a task into a reusable block. Good functions make code easier to read, test, and change. In Android, functions handle button clicks, format text, validate forms, build UI components, and transform API data.
Basic Functions
fun calculateProgress(completed: Int, total: Int): Int {
return if (total == 0) 0 else (completed * 100) / total
}
println(calculateProgress(3, 10))
A function should usually do one clear thing. If the name needs the word and, the function may be doing too much.
Parameters And Return Types
Parameters are inputs. Return values are outputs.
fun buildGreeting(name: String, isPremium: Boolean): String {
return if (isPremium) {
"Welcome back, $name"
} else {
"Hello, $name"
}
}
Kotlin can use expression bodies for short functions:
fun isValidPassword(password: String): Boolean = password.length >= 8
Default Parameters
Kotlin lets you give parameters default values. Callers only provide what they need.
fun showSnackbar(
message: String,
actionLabel: String = "Dismiss",
duration: Int = 3000
) {
// show snackbar
}
showSnackbar("Saved successfully")
showSnackbar("Error occurred", actionLabel = "Retry", duration = 5000)
This is especially visible in Compose. Almost every composable has default parameters so you can write:
Text("Hello")
// instead of
Text(text = "Hello", color = Color.Unspecified, fontSize = TextUnit.Unspecified, ...)
When you see a composable call with only a few arguments, defaults are doing the heavy lifting.
Lambdas
A lambda is a function value. You can store it, pass it, and call it later.
val onComplete: () -> Unit = {
println("Lesson completed")
}
onComplete()
Lambdas are everywhere in Android, especially with Compose:
Button(onClick = { println("Clicked") }) {
Text("Continue")
}
The button does not know what your app should do. It simply accepts a lambda and runs it when the user taps.
Higher-Order Functions
A function that takes another function is called a higher-order function.
fun trackAction(name: String, action: () -> Unit) {
println("Starting $name")
action()
println("Finished $name")
}
This pattern is useful for logging, retries, validation, and UI events.
Practice
Write a function called validateSignup that accepts an email and password and returns a message. Then create a lambda called onSignupClick that prints the validation result.
Summary
Functions turn repeated logic into reusable units. Lambdas let you pass behavior around, which is essential for Compose, callbacks, and clean Android architecture.