SyntaxStudy
Sign Up
Kotlin Function Basics and Default Parameters
Kotlin Beginner 1 min read

Function Basics and Default Parameters

Kotlin functions are declared with the fun keyword and can appear at the top level, inside classes, or nested inside other functions. Return types are written after the parameter list with a colon; functions that return nothing implicitly return Unit, which can be omitted. Default parameter values eliminate the need for multiple overloaded versions of the same function. When calling a function you can also use named arguments, which let you pass values in any order and make call sites self-documenting — especially useful for functions with many parameters of the same type. Single-expression functions can drop the curly braces and return keyword entirely. The compiler infers the return type from the expression on the right-hand side, keeping trivial functions extremely concise.
Example
// Basic function
fun add(a: Int, b: Int): Int {
    return a + b
}

// Single-expression function — return type inferred
fun multiply(a: Int, b: Int) = a * b

// Default parameters
fun greet(name: String, greeting: String = "Hello", punctuation: String = "!") =
    "$greeting, $name$punctuation"

// Vararg parameter
fun sumAll(vararg numbers: Int): Int {
    var total = 0
    for (n in numbers) total += n
    return total
}

// Local function — visible only inside outer function
fun processData(input: String): String {
    fun clean(s: String) = s.trim().lowercase()
    fun validate(s: String) = s.isNotEmpty()

    val cleaned = clean(input)
    return if (validate(cleaned)) cleaned else "invalid"
}

fun main() {
    println(add(3, 4))            // 7
    println(multiply(6, 7))       // 42

    println(greet("Alice"))                          // Hello, Alice!
    println(greet("Bob", punctuation = "."))         // Hello, Bob.
    println(greet(greeting = "Hi", name = "Carol"))  // Hi, Carol!

    println(sumAll(1, 2, 3, 4, 5))   // 15

    val arr = intArrayOf(10, 20, 30)
    println(sumAll(*arr))             // 60 — spread operator

    println(processData("  Kotlin  "))   // kotlin
}