Beginner: Kotlin · Null safety, functions and lambdas · topic 6 of 50 · 30 min
Functions
Explanation
Why functions?
A function is a named, reusable block of code that does one job. Instead of repeating the GST calculation in ten places, you write it once as a function and call it ten times. If the rule changes, you fix one place.
fun withGst(price: Double, ratePercent: Double): Double {
return price + price * ratePercent / 100
}
fun main() {
val total = withGst(1000.0, 18.0)
println(total) // 1180.0
}Unit: returning nothing
A function that only does something (like printing) and returns no useful value has the return type Unit. You can leave it out: fun greet(name: String) { ... } is the same as fun greet(name: String): Unit { ... }.
Single-expression functions
If a function just returns one expression, write = and the expression, without braces or return. Kotlin infers the return type. This style is very common.
fun square(n: Int) = n * n
fun isAdult(age: Int) = age >= 18
fun grade(marks: Int) = if (marks >= 33) "Pass" else "Fail"Default arguments
A parameter can have a default value. Callers may leave it out. In Java you would write several overloaded versions; in Kotlin one function is enough.
fun ticket(from: String, to: String, passengers: Int = 1, classType: String = "Sleeper") =
"$passengers x $classType: $from to $to"
fun main() {
println(ticket("Pune", "Nagpur")) // 1 x Sleeper: Pune to Nagpur
println(ticket("Pune", "Nagpur", 3)) // 3 x Sleeper: Pune to Nagpur
println(ticket("Pune", "Nagpur", classType = "3A")) // 1 x 3A: Pune to Nagpur
}Named arguments
You can name arguments when calling: sendSms(to = "98...", text = "Hi", urgent = true). Named arguments make calls with many parameters, especially Booleans, much easier to read, and you can give them in any order. Jetpack Compose code uses named arguments everywhere.
vararg: any number of arguments
fun total(vararg prices: Int): Int {
var sum = 0
for (p in prices) sum += p
return sum
}
fun main() {
println(total(120, 80, 45)) // 245
println(total()) // 0
}Top-level and local functions
Kotlin functions do not need to live inside a class. A function written directly in a file is a top-level function, usable from anywhere in the module. You can also define a function inside another function (a local function) for a small helper that nobody else needs.
Common mistakes
- Forgetting the return type when using braces and return: the function then returns Unit, and return value is an error. Add : Type.
- Using return inside a single-expression function body. With =, there is no return keyword.
- Positional Boolean arguments like save(true, false). Use named arguments: save(sync = true, notify = false).
- Mixing named and positional arguments in a confusing order. Keep positional ones first.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Functions · 1/6
A function is a named block of code that does one job. You write it once and call it many times.
Prefer a video by a teacher? Find free videos on “kotlin functions default named arguments single expression” on YouTube ↗
In real life: Formatting rupee amounts
An expense-tracker app shows money everywhere: lists, totals, charts. One function formatRupees(amount, showPaise = true) is used on every screen. Most screens use the default, while the chart labels call formatRupees(x, showPaise = false) for shorter text.
fun formatRupees(paise: Long, showPaise: Boolean = true): String {
val rupees = paise / 100
val rest = paise % 100
return if (showPaise) "Rs $rupees.${rest.toString().padStart(2, '0')}" else "Rs $rupees"
}
fun main() {
println(formatRupees(123456)) // Rs 1234.56
println(formatRupees(123456, showPaise = false)) // Rs 1234
}Practice (0/3 done)
What does this print? fun greet(name: String, greeting: String = "Hello") = "$greeting, $name!" fun main() { println(greet("Ira", greeting = "Namaste")) }
What is the return type of fun log(msg: String) { println(msg) }?
Write fun emi(principal: Double, yearlyRate: Double = 9.0, months: Int = 12): Double. Call it three ways: with only principal, with principal and months by name, and with all three. Then write fun average(vararg marks: Int): Double that returns 0.0 for no marks.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Lambdas and higher-order functionsNull safety, functions and lambdas · same module
- Extension functions and scope functionsNull safety, functions and lambdas · same module
- Parameters in depth: optional, named, ref, out, params, overloadingC# and .NET · Decisions, loops and methods
- Functions, statements and expressionsRust Programming · Types, control flow and functions
- FunctionsFrontend Web Development · JavaScript basics
- Functions: declarations, expressions and returnJavaScript Programming (language in depth) · Functions and closures
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Which is a valid single-expression function?
Answer: fun double(x: Int) = x * 2
Use = with an expression; parameter types are required.
Why are named arguments useful?
Answer: They make calls with many parameters clear and order-independent
Names document what each value means.
Inside fun f(vararg n: Int), what does n behave like?
Answer: An array of Int
vararg parameters are arrays inside the function.
Do Kotlin functions have to be inside a class?
Answer: No, top-level functions are allowed
Kotlin supports top-level functions.
Can you overload two methods that differ only in return type?Related
Answer: No, the parameter lists must differ
The compiler chooses an overload by arguments, so return type alone is not enough (CS0111).
From Parameters in depth: optional, named, ref, out, params, overloading
What does a function without -> return?Related
Answer: The unit type ()
Without a return type, the function returns ().
A variable is declared with const inside a function. Where can it be used?Related
Answer: Only inside that function
let and const are block-scoped: they live only inside their { }.
From Functions
function f() { return 1; console.log("hi"); } What happens when f() runs?Related
Answer: Returns 1 and never prints
return ends the function; the next line is never reached.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 2 more topics in “Null safety, functions and lambdas” before its exam: Lambdas and higher-order functions, Extension functions and scope functions.
- Module 2 exam: Null safety, functions and lambdas · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Classes, objects and collections. 50 topics left in the course before the final exam.