
Functions in Kotlin
📌 Functions in Kotlin
In Kotlin, functions are a fundamental building block used to group code that performs a specific task. Functions can be defined at the top level, inside classes (member functions), or even within other functions (local functions). Kotlin also supports higher-order functions, lambda functions, and inline functions.
✅ 1. Basic Function Declaration
The fun
keyword is used to define a function in Kotlin.
📌 Syntax:
fun (parameter1: Type, parameter2: fun (a: Int, b: fun () { println(add(5, 10)) // Output: 15}
fun
→ Keyword to declare a function.add
→ Function name.a: Int, b: Int
→ Parameters.: Int
→ Return type.
✅ 2. Single Expression Functions
If a function contains a single expression, you can write it concisely using the =
operator.
📌 Example:
fun (a: Int, b: fun () { println(multiply(4, 5)) // Output: 20}
No need for
return
or curly braces{}
.
✅ 3. Functions Without Return Value (Unit)
Functions that don't return any value return Unit
, which is equivalent to void
in other languages.
📌 Example:
fun (name: String): fun (name: String = fun () { greet() // Output: Hello, Guest! greet("Alice") // Output: Hello, Alice!}
📌 Example: Named Arguments
fun (name: String, age: fun () { displayDetails(age = 30, country = "India", name = "Vikash")}
Output:
Vikash is 30 years old from India.
Named arguments improve readability.
✅ 5. Variable Number of Arguments (Varargs)
You can pass a variable number of arguments using vararg
.
📌 Example:
fun (vararg numbers: fun () { println(sum(1, 2, 3, 4, 5)) // Output: 15}
vararg
allows you to pass multiple integers.
✅ 6. Higher-Order Functions
Functions that take other functions as parameters or return functions are called higher-order functions.
📌 Example:
fun (a: Int, b: fun (a: Int, b: fun (a: Int, b: fun () { println(calculate(10, 5, ::add)) // Output: 15 println(calculate(10, 5, ::multiply)) // Output: 50}
operation
is a function type(Int, Int) -> Int
.
✅ 7. Lambda Functions
Lambdas are anonymous functions that can be used as expressions.
📌 Example:
val multiply = { a: Int, b: Int -> a * b }fun () { println(multiply(4, 5)) // Output: 20}
{ a: Int, b: Int -> a * b }
→ Lambda expression.
✅ 8. Inline Functions
Inline functions improve performance by copying the function body into the call site, reducing function call overhead.
📌 Example:
inline fun (action: () -> Unit) { println(fun main() { execute { println("Executing task...") }}
Output:
Before actionExecuting task...After action
✅ Conclusion
Basic Functions → Use
fun
to declare functions with parameters and return values.Single Expression Functions → Use
=
for short functions.Default and Named Arguments → Provide flexibility in function calls.
Varargs → Pass multiple values.
Higher-Order Functions → Pass functions as parameters.
Lambda Functions → Write concise anonymous functions.
Inline Functions → Optimize performance.