Function Basics in Kotlin

From the Kotlin cheat sheet · Functions · verified Jul 2026

Function Basics

Function syntax and parameters

kotlin
// Basic function
fun greet(name: String): String {
    return "Hello, $name!"
}

// Single expression function
fun add(a: Int, b: Int) = a + b

// Default parameters
fun connect(host: String = "localhost", port: Int = 8080) {
    println("Connecting to $host:$port")
}

// Named arguments
connect(port = 3000, host = "example.com")

// Unit return type (void)
fun printMessage(msg: String): Unit {
    println(msg)
}
// Unit can be omitted
fun log(msg: String) {
    println("[LOG] $msg")
}
💡 Single expression functions use = instead of braces
⚡ Named arguments improve readability and allow skipping defaults
📌 tailrec optimizes tail recursive functions to loops
🟢 Infix functions allow natural DSL-like syntax

More Kotlin tasks

Back to the full Kotlin cheat sheet