How do I define and call functions in Kotlin?

In Kotlin, defining and calling functions is straightforward and follows a clear syntax. Here’s how you can define and use functions:

Defining a Function

The fun keyword is used to define a function in Kotlin.

Basic Syntax:

fun functionName(parameters: ParameterType): ReturnType {
    // Function body
    return someValue // Optional if the return type is Unit (void equivalent in Kotlin)
}

Example – A Function without Parameters and Return Type (Unit):

fun sayHello() {
    println("Hello, World!")
}

Function with Parameters:

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

Function with Parameters and a Return Type:

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

Calling a Function

You simply call the function by its name and pass the required arguments (if any).

Examples:

  1. Calling a Function without Arguments:
    sayHello() // Output: Hello, World!
    
  2. Calling a Function with Arguments:
    greet("Alice") // Output: Hello, Alice!
    
  3. Calling a Function with Return Value:
    val sum = add(5, 3)
    println("Sum: $sum") // Output: Sum: 8
    

Default Parameters

Functions in Kotlin can have default parameter values. If a parameter is not provided during function call, the default value is used.

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

// Usage
greet()          // Output: Hello, Guest!
greet("Alice")   // Output: Hello, Alice!

Single-Expression Functions

If a function contains only a single expression, you can use the = symbol without curly braces:

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

// Usage
println(square(4)) // Output: 16

Named Arguments

When calling a function, you can specify arguments by their parameter names for better readability.

fun displayInfo(name: String, age: Int) {
    println("Name: $name, Age: $age")
}

// Usage
displayInfo(age = 25, name = "John") // Output: Name: John, Age: 25

Vararg Parameters (Variable Number of Arguments)

You can pass a variable number of arguments to a function using the vararg keyword.

fun printAll(vararg items: String) {
    for (item in items) {
        println(item)
    }
}

// Usage
printAll("Apple", "Banana", "Cherry")
// Output:
// Apple
// Banana
// Cherry

Higher-Order Functions (Functions that Take or Return Functions)

Function Taking Another Function as a Parameter:

fun applyOperation(x: Int, y: Int, operation: (Int, Int) -> Int): Int {
    return operation(x, y)
}

// Usage
val result = applyOperation(4, 5) { a, b -> a + b } // Lambda as a parameter
println(result) // Output: 9

Function Returning Another Function:

fun getMultiplier(factor: Int): (Int) -> Int {
    return { number -> number * factor }
}

// Usage
val multiplier = getMultiplier(3)
println(multiplier(5)) // Output: 15

By using these techniques, you can write concise and powerful functions in Kotlin.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.