Function Basics
In this page:
Declaring a Function
A function starts with fun, followed by its name, a parenthesized parameter list, an optional return type, and a body in curly braces.
Example: Declaring a Function
fun greet(name: String): String {
return "Hello, $name!"
}
fun main() {
println(greet("Kotlin"))
}
Login to try C/C++/Java/PHP code in the editor
Functions with No Return Value
A function that only performs an action, like printing, and produces no useful value has a return type of Unit, which can be omitted since it is the default.
Example: Functions with No Return Value
fun printBanner(text: String) {
println("=== $text ===")
}
fun main() {
printBanner("Welcome")
}
Login to try C/C++/Java/PHP code in the editor
Multiple Parameters
A function can take several typed parameters separated by commas, and every one of them (unless it has a default) must be supplied at the call site.
Example: Multiple Parameters
fun add(a: Int, b: Int): Int {
return a + b
}
fun main() {
println("Sum: ${add(3, 4)}")
}
Login to try C/C++/Java/PHP code in the editor
Calling Functions
Calling a function uses its name followed by parentheses containing arguments in the same order as the parameters were declared.
Example: Calling Functions
fun multiply(a: Int, b: Int): Int {
return a * b
}
fun main() {
val result = multiply(6, 7)
println("6 x 7 = $result")
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting to declare a return type when a function does not implicitly return
Unit, causing a compiler error. - Confusing parameter order when calling a function positionally, sending values to the wrong parameters.
- Not realizing a function with no explicit
returnand a block body implicitly returnsUnit, not the last expression's value.
- Functions are declared with
fun name(parameters): ReturnType { body }. - A function with no meaningful return value has (or can omit) a return type of
Unit. - Parameters are typed and, unless given defaults, must all be supplied when calling the function.
- The
returnkeyword sends a value back from a block-bodied function.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: