In Kotlin, while defining a function, we have many optional features and variations that make functions more flexible and easier to use. In this article, we’ll go through these different ways of defining functions one by one, using simple explanations and examples.
Function Definition
Here is the standard way to define a function in Kotlin:
Syntax:
[Visibility Modifier] fun functionName(argumentName: Type, ...): ReturnType {
// function body
return value
}
Normally, It is the proper way for defining a function in Kotlin.
Example:
private fun addNumbers(a: Int, b: Int): Int {
val c: Int = a + b
return c
}
In this example:
- Function name: addNumbers
- Arguments: a and b (both of type Int)
- Return type: Int
- Visibility: private (because of the visibility modifier)
1. Visibility Modifiers (Public / Private / Protected / Internal)
In Kotlin, when we define a function, the visibility modifier is optional. If we don’t specify it, the function is treated as public by default.
Example:
// Private function
private fun addNumbers(a: Int, b: Int): Int {
return a + b
}
// Public function (default)
fun addNumbers(a: Int, b: Int): Int {
return a + b
}
Both functions do the same work, but the first one is private (accessible only within its file), and the second one is public (accessible from everywhere).
2. Single Expression Functions
In Kotlin, if a function contains only one expression, we can simplify it by removing the curly braces {} and using the = symbol instead.
Example:
fun addNumbers(a: Int, b: Int): Int = a + bWe can simplify it even further because Kotlin can infer the return type:
fun addNumbers(a: Int, b: Int) = a + bBoth of the above functions are exactly the same.
3. Return Type
In Kotlin, we must declare the return type if the function returns something. If the function returns nothing, we can either specify the return type as Unit (which is similar to void in Java), or omit it and kotlin will assume the function returns Unit.
Example: Explicit Unit return type
fun printNumber(a: Int): Unit {
println(a)
}
Omitting Unit -
fun printNumber(a: Int) {
println(a)
}
Both functions above are the same, because Kotlin automatically treats them as functions returning nothing (Unit).
4. Named Arguments
When a function has many parameters, remembering their positions can be hard. Kotlin allows us to use named arguments, where we specify the name of the parameter during the function call. With named arguments we can pass parameters in any order and the compiler matches them based on the name, not their position.
Example:
fun main() {
val result1 = addNumbers(arg1 = 5, arg2 = 10) // using named arguments
val result2 = addNumbers(arg2 = 10, arg1 = 5) // order doesn't matter
println("Result 1: $result1")
println("Result 2: $result2")
}
fun addNumbers(arg1: Int, arg2: Int): Int {
return arg1 + arg2
}
Output:
Result 1: 15
Result 2: 15
This makes function calls clearer and reduces mistakes when passing values.