← Back to Kotlin Course | Chapter 4: Functions | Lesson 1 of 7

Function Basics

A function is a named recipe of steps that you can reuse any time you need the computer to do that same job again.

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

markup
fun greet(name: String): String {
    return "Hello, $name!"
}

fun main() {
    println(greet("Kotlin"))
}

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

markup
fun printBanner(text: String) {
    println("=== $text ===")
}

fun main() {
    printBanner("Welcome")
}

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

markup
fun add(a: Int, b: Int): Int {
    return a + b
}

fun main() {
    println("Sum: ${add(3, 4)}")
}

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

markup
fun multiply(a: Int, b: Int): Int {
    return a * b
}

fun main() {
    val result = multiply(6, 7)
    println("6 x 7 = $result")
}
Common Mistakes
  1. Forgetting to declare a return type when a function does not implicitly return Unit, causing a compiler error.
  2. Confusing parameter order when calling a function positionally, sending values to the wrong parameters.
  3. Not realizing a function with no explicit return and a block body implicitly returns Unit, not the last expression's value.
Chapter Summary
  • 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 return keyword 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.