Functions and return values
Functions and return values
A report calculation should not be copied for every student. A function groups statements behind a name, accepts inputs and can return a result. Its parameter types and return type make the contract visible before you inspect its body.
What you’ll learn
- Return a reusable computed result.
- Reject an invalid averaging count.
Functions and return values in the example
Call with inputs
A report calculation should not be copied for every student.
Call with inputsCompute a result
A function declaration uses fun, parameter types and an optional return type.
Compute a resultReturn to caller
The precondition accepts count two, then converting total avoids integer truncation.
Return to caller
Understand functions and return values
A function declaration uses fun, parameter types and an optional return type. Returning a value lets a caller use it independently of printing. Kotlin can use an expression body for a short function; local names remain within their declared scope.
Follow functions and return values
Save the complete source as Main.kt and use the Kotlin/JVM environment. No separate input file is needed.
Kotlin/JVM · complete program
fun average(total: Int, count: Int): Double {
require(count > 0) { "Count must be positive" }
return total.toDouble() / count
}
fun main() { println(average(155, 2)) }Expected output
77.5Follow the execution
The precondition accepts count two, then converting total avoids integer truncation. The returned Double is 77.5. Printing is performed by main, so the function itself can also support another kind of caller.
Try this in the Kotlin compiler by pasting the complete program.
Practice: Functions and return values
Your task: What happens if count is zero?
Kotlin/JVM · complete program
fun average(total: Int, count: Int): Double {
require(count > 0) { "Count must be positive" }
return total.toDouble() / count
}
fun main() { println(average(155, 2)) }Worked answer
Require rejects the input with an IllegalArgumentException before division. The caller needs a suitable policy for invalid inputs.
Functions and return values: the important boundary
Choose explicit error or result contracts for ordinary invalid user input. Recursion needs a stopping case, and tailrec optimization applies only to suitable recursive calls. A function’s type contract does not prove its domain calculation is correct.
Check your understanding
Functions and return values: what to keep in mind
Require rejects the input with an IllegalArgumentException before division. The caller needs a suitable policy for invalid inputs. Choose explicit error or result contracts for ordinary invalid user input.
Further reading: official Kotlin documentation for this topic.
Reaching the recap and completing the quizzes are separate milestones.