Kotlin Functions

Kotlin Functions

In Kotlin, functions are used to organize code into reusable blocks. They help make programs clean, readable, and easy to maintain.


1. Basic Function

fun greet() {
println("Hello, Kotlin")
}

Calling the function:

greet()

2. Function with Parameters

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

Call:

add(10, 20)

3. Function with Return Value

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

Call:

val result = add(5, 3)
println(result)

4. Single-Expression Function (Short Form)

fun add(a: Int, b: Int) = a + b

5. Function with Default Parameters

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

greet()
greet("Sanjit")


6. Named Arguments

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

userInfo(age = 22, name = "Rahul")


7. Function with Unit Return Type

If a function does not return a value, its return type is Unit.

fun showMessage(): Unit {
println("Welcome")
}

(Unit can be omitted)


8. Function Overloading

Multiple functions with the same name but different parameters.

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

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


9. Recursive Function

A function that calls itself.

fun factorial(n: Int): Int {
return if (n == 1) 1 else n * factorial(n - 1)
}

10. Lambda Function (Anonymous Function)

val sum = { a: Int, b: Int -> a + b }

println(sum(3, 4))


Summary

  • Functions improve code reusability

  • Support parameters, return values, defaults

  • Short syntax available

  • Supports recursion and lambdas

You may also like...