Kotlin Functions

Basic Function

fun greet() {
    println("Hello from Kotlin!")
}

Functions start with the fun keyword. The return type is optional if Unit (like void).

Function with Parameters

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

Parameters follow the name: Type format.

Function with Return Value

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

Specify the return type after the parameter list using :.

Single-Expression Functions

fun square(x: Int): Int = x * x

Use = instead of curly braces for concise one-liners.

Default Parameter Values

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

Default values let you call functions with fewer arguments.

Named Arguments

You can call parameters out of order by naming them:

Loading...
Output:

Function with Vararg

fun sum(vararg numbers: Int): Int {
    return numbers.sum()
}

println(sum(1, 2, 3, 4))

vararg lets you pass any number of arguments of the same type.

Functions Returning Unit

If a function doesn't return anything meaningful, use Unit or omit it:

fun log(message: String): Unit {
    println("LOG: $message")
}

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic