Sobes.tech
Junior

How are functions described in Kotlin?

sobes.tech AI

Answer from AI

Functions are declared using the keyword fun, followed by the function name, an optional list of parameters in parentheses, a colon, and an optional return type. The body of the function is enclosed in curly braces. If the return type is omitted, the function returns Unit (equivalent to void in other languages).

// Function without parameters and return value
fun greet() {
    println("Hello!")
}

// Function with parameters
fun add(x: Int, y: Int): Int {
    return x + y
}

// Function with a single expression (concise body syntax)
fun multiply(a: Int, b: Int) = a * b

Function parameters are declared in the format parameterName: Type. Default values for parameters can be specified.

fun sendMessage(message: String, sender: String = "Unknown") {
    println("$sender: $message")
}

Functions can be declared at the top level of a file or as members of classes, objects, or interfaces.

  • Top-level functions: Declared outside classes.

    fun calculateArea(radius: Double): Double {
        return Math.PI * radius * radius
    }
    
  • Member functions: Declared inside classes.

    class MyClass {
        fun doSomething() {
            println("Doing something.")
        }
    }
    
  • Extension functions: Allow "adding" functions to existing classes without modifying their source code.

    fun String.reverseAndUpperCase(): String {
        return this.reversed().toUpperCase()
    }
    

Lambda expressions and anonymous functions are function literals that can be passed as arguments or assigned to variables.

val sum: (Int, Int) -> Int = { x, y -> x + y }
val greeting = { name: String -> "Hello, $name!" }

Higher-order functions accept functions as parameters or return functions.

fun operate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    return operation(a, b)
}

val result = operate(5, 3, { x, y -> x * y }) // result = 15

Function overloading (different functions with the same name but different signatures) is supported automatically.

fun printInfo(name: String) {
    println("Name: $name")
}

fun printInfo(age: Int) {
    println("Age: $age")
}
How are functions described in Kotlin? — Kotlin - sobes.tech