Skip to main content
Kotlin Basics
CHAPTER 09 Beginner

Functions in Kotlin

Updated: May 18, 2026
5 min read

# CHAPTER 9

Functions in Kotlin

1. Chapter Introduction

If you are building an app to calculate taxes, you don't want to rewrite the calculation formula every time a user makes a purchase. Instead, you wrap that formula in a Function. Functions are blocks of reusable code that perform a specific task. In this chapter, we will learn how to declare functions, pass data into them (parameters), return data from them, and utilize Kotlin's modern features like Named Arguments and Default Arguments.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Declare standard functions using the fun keyword.
  • Define parameters and return types.
  • Create single-expression functions.
  • Use Default Arguments to reduce function overloading.
  • Use Named Arguments to improve code readability.

3. Declaring a Basic Function

We have already been using a function: fun main(). Let's create our own. A function declaration starts with the fun keyword, followed by the function name, parentheses (), and curly braces {}.
kotlin
12345678910
// Declaring the function
fun greetUser() {
    println("Welcome to the application!")
}

fun main() {
    // Calling the function
    greetUser()
    greetUser() // Reusable!
}

4. Parameters and Return Types

Most functions need input data to do their job, and need to send a result back.
  • Parameters: Variables passed into the function (inside the ()). You MUST define their type.
  • Return Type: The type of data the function sends back. Defined after a colon : at the end of the parentheses. If a function returns nothing, it technically returns Unit (similar to void in Java), but you don't need to write it.
kotlin
12345678910
// Function takes two Int parameters and returns an Int
fun addNumbers(a: Int, b: Int): Int {
    val sum = a + b
    return sum // Sends the result back to the caller
}

fun main() {
    val result = addNumbers(10, 5) // Passes 10 and 5 into the function
    println("The sum is $result")
}

5. Single-Expression Functions (Concise Syntax)

If your function only does one thing (like returning a math calculation), you can remove the curly braces {} and the return keyword, using an =. Kotlin will infer the return type automatically!
kotlin
1234567
// Standard way
fun multiply(a: Int, b: Int): Int {
    return a * b
}

// Single-expression way (Idiomatic Kotlin)
fun multiplyConcise(a: Int, b: Int) = a * b

6. Default Arguments (Eliminating Overloading)

In Java, if you have a function that takes a name and an optional title, you have to write two separate functions (Overloading). Kotlin solves this brilliantly with Default Arguments.

You can assign a default value to a parameter right in the declaration. If the caller doesn't provide it, the default is used.

kotlin
123456789
// 'title' has a default value of "User"
fun printProfile(name: String, title: String = "User") {
    println("Name: $name | Title: $title")
}

fun main() {
    printProfile("Alice", "Admin") // Overrides default -> Title: Admin
    printProfile("Bob")            // Uses default -> Title: User
}

7. Named Arguments (Improving Readability)

If a function has 5 parameters, calling createUser(true, false, "Admin", 5) is impossible to read. What does true mean? Kotlin allows you to explicitly name the arguments when calling the function. You can even change their order!
kotlin
12345678
fun formatText(text: String, isBold: Boolean, isItalic: Boolean) {
    // ... formatting logic
}

fun main() {
    // Calling with Named Arguments makes it perfectly clear
    formatText(text = "Hello", isItalic = true, isBold = false)
}

8. Mini Project: Tax Calculator

Let's build a robust function that uses default parameters.
kotlin
123456789101112131415161718
// Default tax rate is 10% (0.1)
fun calculateTotal(price: Double, taxRate: Double = 0.1): Double {
    val taxAmount = price * taxRate
    return price + taxAmount
}

fun main() {
    val phonePrice = 1000.0
    
    // Normal purchase (uses default 10% tax)
    val standardTotal = calculateTotal(price = phonePrice)
    
    // Duty-free purchase (we pass 0% tax)
    val dutyFreeTotal = calculateTotal(price = phonePrice, taxRate = 0.0)
    
    println("Standard Total: $$standardTotal")
    println("Duty Free Total: $$dutyFreeTotal")
}

9. Common Mistakes

  • Mutating Parameters: In Kotlin, function parameters are read-only (val) by default. You cannot do fun add(a: Int) { a = 10 }. This is by design to prevent accidental side effects. If you need to change it, assign it to a new var inside the function.
  • Forgetting the Return Type: If you use the return keyword inside a standard function block {}, you MUST explicitly define the return type (e.g., : Int). Only single-expression functions = can infer return types.

10. Best Practices

  • Use Single-Expression syntax: Whenever your function is just returning a simple calculation or a when expression, use the = syntax. It keeps your codebase incredibly clean.

11. Exercises

  1. 1. Write a function greet(name: String). It should print "Hello, $name".
  1. 2. Write a single-expression function isEven(num: Int) = num % 2 == 0.
  1. 3. Call both in main().

12. MCQs with Answers

Question 1

What keyword is used to define a function in Kotlin?

Question 2

Where do you declare the return type of a standard function?

Question 3

If a function does not return any data, what is its implicit return type in Kotlin?

Q4. Can you reassign a parameter's value inside a function (e.g., a = 10)? a) Yes b) No, function parameters in Kotlin are strictly read-only (val) Answer: b) No, parameters are read-only.
Question 5

What syntax allows you to omit the {} and return keyword for short functions?

Question 6

What does assigning a value to a parameter in the function declaration do (e.g., title: String = "User")?

Question 7

What problem do Default Arguments solve compared to Java?

Question 8

What feature allows you to specify exactly which parameter you are passing data to, improving readability?

Q9. When using Named Arguments, do you have to pass them in the exact order they were declared? a) Yes b) No, you can pass them in any order Answer: b) No, you can pass them in any order.
Question 10

What is the output of fun square(x: Int) = x * x if called with square(4)?

13. Interview Questions

  • Q: Contrast Kotlin's Default Arguments with Java's Method Overloading. Why is Kotlin's approach considered more maintainable?
  • Q: Explain what a Single-Expression Function is and write a quick example on the whiteboard.

14. Summary

Functions are the building blocks of modular programming. Kotlin refines the function syntax heavily, ensuring that parameters are immutable to prevent bugs. By providing Default Arguments and Named Arguments, Kotlin ensures that function calls remain flexible and highly readable, even when dealing with complex configurations.

15. Next Chapter Recommendation

So far, a variable can only hold one piece of data. What if we need to store a list of 100 students? In Chapter 10: Arrays and Collections, we will learn how to group data together using Lists, Sets, and Maps.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·