100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Kotlin

Functions in Kotlin

Learn how to declare, call, and simplify functions in Kotlin, including single-expression syntax and the Unit type.

Functions & LambdasBeginner7 min readJul 8, 2026
Analogies

Introduction

A function is a reusable block of code that performs a specific task. Kotlin functions are declared with the fun keyword, and they can accept parameters, return a value, or return nothing meaningful (represented by the type Unit). Kotlin's function syntax is concise compared to Java, letting you skip boilerplate like explicit void or verbose return-type declarations for simple cases.

🏏

Cricket analogy: A bowler's run-up (the fun declaration) takes inputs like pace and line, and delivers either a wicket (a return value) or simply completes the over with nothing to show (Unit), and unlike an old-school coaching manual's lengthy instructions, Kotlin lets you describe the action in one clean line.

Syntax

kotlin
fun name(param1: Type1, param2: Type2): ReturnType {
    // function body
    return someValue
}

// Single-expression function (return type inferred)
fun square(x: Int) = x * x

// Function returning Unit (like void in Java)
fun logMessage(message: String): Unit {
    println(message)
}

Explanation

The fun keyword starts the declaration, followed by the function name, a parameter list in parentheses, and an optional return type after a colon. If a function body is a single expression, you can drop the curly braces and use = instead, letting the compiler infer the return type. Functions that don't return a meaningful value have a return type of Unit, which can be omitted entirely since it is the default.

🏏

Cricket analogy: Writing fun runsScored(balls: Int): Int = balls * strikeRate lets a scorer skip a long-form over-by-over tally sheet for a quick single-line calculation, and if the function just logs an appeal instead of returning runs, the Unit result type doesn't even need to be written.

Example

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

fun multiply(a: Int, b: Int) = a * b

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

fun main() {
    println(add(3, 4))
    println(multiply(3, 4))
    greet("Kotlin")
}

Output

kotlin
7
12
Hello, Kotlin!

Key Takeaways

  • Functions are declared using the fun keyword.
  • A single-expression function can omit braces and use = with an inferred return type.
  • Unit is Kotlin's equivalent of void and can be omitted from the signature.
  • Parameters must specify a type; return type comes after a colon.
  • Functions can be declared at the top level, inside classes, or nested inside other functions.

Practice what you learned

Was this page helpful?

Topics covered

#Kotlin#KotlinProgrammingStudyNotes#Programming#FunctionsInKotlin#Functions#Syntax#Explanation#Example#StudyNotes#SkillVeris