Functions

Reviewed & published by Brayan K

Kotlin is a modern, concise language where functions are first-class building blocks — declared with fun, they package reusable logic and return values cleanly.

Part of the free Kotlin course at LearnCodingFast — hands-on lessons with worked examples and the output they print, plus practice exercises and a quick quiz.

By the end of this lesson you'll define functions with typed parameters and return types, write compact single-expression functions, and understand Unit.

What You'll Learn in This Lesson

1️⃣ Declaring Functions

A Kotlin function starts with fun, followed by a name, parameters written as name: Type, and an optional return type after a colon. Inside, return hands a value back to the caller.

// Declare a function with 'fun'. Parameters are name: Type.
// The return type comes after the parameter list, following a colon.
fun add(a: Int, b: Int): Int {
    return a + b
}

// A function that returns nothing has return type Unit (you can omit it).
fun greet(name: String) {
    println("Hello, $name!")
}

fun main() {
    val sum = add(3, 4)
    println("3 + 4 = $sum")      // -> 3 + 4 = 7

    greet("Linus")               // -> Hello, Linus!
}

The greet function returns nothing useful, so its type is Unit — Kotlin's equivalent of void. You can omit : Unit entirely.

2️⃣ Single-Expression Functions

When a function is just one expression, you can replace the braces and return with an = sign. The return type is inferred. This is one of the most idiomatic patterns in Kotlin for small, focused functions.

// Single-expression functions: replace the braces and 'return'
// with an = sign. The return type is inferred.
fun square(n: Int) = n * n

fun max(a: Int, b: Int) = if (a > b) a else b

// Functions can call other functions, building up behaviour.
fun describe(n: Int): String =
    if (n % 2 == 0) "$n is even" else "$n is odd"

fun main() {
    println(square(5))           // -> 25
    println(max(8, 3))           // -> 8
    println(describe(7))         // -> 7 is odd
    println(describe(square(2))) // -> 4 is even
}

Functions compose naturally: describe(square(2)) first squares 2 to get 4, then describes it. Small functions that each do one thing are the foundation of clean code.

Your turn. Replace each TODO, then run and compare.

// 🎯 YOUR TURN — replace each TODO then run main()

// 1) Write a single-expression function that returns the larger of two Ints.
fun larger(a: Int, b: Int) = if (a > b) a TODO b   // 👉 replace TODO with 'else'

// 2) Write a function that returns true if a number is even.
fun isEven(n: Int): Boolean {
    return n % 2 TODO 0          // 👉 replace TODO with '=='
}

fun main() {
    println(larger(10, 4))       // expect 10
    println(isEven(6))           // expect true
}

Mini-Challenge: A Temperature Converter

Write two small functions — one for the maths, one for the label — and combine them in main().

// 🎯 MINI-CHALLENGE: a temperature converter.
// Save as Temp.kt and run main().
//
// 1. Write fun cToF(c: Double): Double that returns c * 9 / 5 + 32.
//    (Try writing it as a single-expression function.)
// 2. Write fun label(c: Double): String that returns
//    "freezing" if c <= 0, "hot" if c >= 30, else "mild".
// 3. In main(), print the Fahrenheit value and label for 25.0.
//
// ✅ Example output:
//    25.0C = 77.0F (mild)

fun main() {
    // your code here
}

Common Errors (and the fix)

Pro Tips

📋 Quick Reference — Functions

ConceptKotlin Syntax
Block functionfun add(a: Int, b: Int): Int { return a + b }
Single-expressionfun sq(n: Int) = n * n
No return valuefun log(m: String) { }
Call a functionadd(3, 4)
Return two valuesreturn Pair(a, b)

🎉 Lesson Complete!

Practice quiz

Which keyword declares a function in Kotlin?

  • func
  • def
  • fun
  • function

Answer: fun. Kotlin functions are declared with the fun keyword.

How is a parameter written in a Kotlin function?

  • name: Type
  • Type name
  • var name
  • (Type) name

Answer: name: Type. Parameters are written as name: Type, with the type after the name.

Where does the return type appear in a function signature?

  • Before the function name
  • After the parameter list, following a colon
  • Inside the body only
  • It is never written

Answer: After the parameter list, following a colon. The return type comes after the parameter list, following a colon.

What is the return type of a function that returns nothing meaningful?

  • Void
  • Null
  • Nothing
  • Unit

Answer: Unit. Such a function returns Unit, Kotlin's equivalent of Java's void.

What is a single-expression function?

  • A function with no parameters
  • One written with = instead of braces and return, with the type inferred
  • A function that returns multiple values
  • A function inside a class only

Answer: One written with = instead of braces and return, with the type inferred. When the body is one expression you can use = and drop braces and return; the type is inferred.

In 'fun square(n: Int) = n * n', what is the return type?

  • Inferred as Int
  • String
  • Unit
  • Must be declared explicitly or it fails

Answer: Inferred as Int. The return type Int is inferred from the expression n * n.

How is Unit different from Java's void?

  • Unit cannot be used at all
  • There is no difference in any sense
  • Unit is a real type with a single value, fitting the everything-is-an-expression model
  • Unit means the function throws

Answer: Unit is a real type with a single value, fitting the everything-is-an-expression model. Unit is a real type with one value, unlike void which is not a value.

What lets you call add(b = 4, a = 3) with order not mattering?

  • Default arguments
  • Named arguments
  • Varargs
  • Operator overloading

Answer: Named arguments. Named arguments let you pass arguments by name so order doesn't matter.

Can a non-Unit function skip returning a value on some path?

  • Yes, it returns null
  • No, it must return on every path or the compiler flags it
  • Yes, it returns Unit
  • Only inside loops

Answer: No, it must return on every path or the compiler flags it. A non-Unit function must return a value on every path; the compiler enforces this.

What is a clean way to return two related values from a function?

  • Use global variables
  • Throw them as an exception
  • Print them instead
  • Return a Pair (or a small data class) and destructure it

Answer: Return a Pair (or a small data class) and destructure it. Return a Pair or small data class, then destructure with val (a, b) = result.

Continue this course

Frequently asked questions

What is a single-expression function?

When a function's body is a single expression, you can drop the curly braces and the return keyword and write it with an = sign instead: fun square(n: Int) = n * n. The return type is inferred from the expression, though you may state it explicitly for clarity. This style is very common in Kotlin for small, pure functions and keeps code concise and readable.

What is Unit and how is it different from void?

Unit is Kotlin's type for functions that don't return a meaningful value — the equivalent of void in Java. The difference is that Unit is a real type with a single value, so it fits into Kotlin's everything-is-an-expression model. You almost never write : Unit explicitly; if a function has no return type annotation and returns nothing, it returns Unit automatically.

Does the order of parameters matter when I call a function?

When you pass arguments positionally, yes — the first argument fills the first parameter, and so on. However, Kotlin also lets you pass named arguments like add(b = 4, a = 3), in which case order doesn't matter and the code is clearer. Named arguments and default values are powerful features you'll explore fully in the 'Default & Named Arguments' lesson.

Can a function return more than one value?

Not directly, but you have good options. You can return a small data class holding the values, or use one of Kotlin's built-in Pair or Triple types, for example return Pair(name, age). The caller can then destructure it with val (name, age) = result. For anything beyond two or three related values, a named data class is usually the cleanest choice.