Kotlin Function – Default Arguments

Default Arguments : Kotlin supports default argument values assigned to parameters in function definition. The function is allowed to call with no argument passed for a parameter when a default value is specified in the definition.

In a function definition, mix of parameters with and without default values is allowed. Usually, when there is such a mix, the parameters with default values are mentioned at the last of parameters list in the definition, so that when an argument is not passed, default value would be picked up.

Syntax to define default arguments

The syntax to define default arguments in Kotlin is

fun funName(param1 : Type, param2: Type = DefaultValue){ }
  • Arguments for parameters having default values are optional.
  • Arguments for parameters with no default values are mandatory as usual.

Example 1 – Kotlin Default Arguments

In the following example, we shall define a function which calculates the sum of two numbers passed as arguments to it. When no arguments are passed, it considers the default argument values provided in the function definition.

Kotlin Program – example.kt

fun main(args: Array<String>) {

    // function call with arguments
    val sum1 = add(5, 6) // output : 11
    println(sum1)

    // function call with no arguments
    val sum2 = add() // output : 2
    println(sum2)

}

/**
 * add function with parameters a, b
 * a : default argument is 1
 * b : default argument is 1
 */
fun add(a:Int = 1, b:Int = 1): Int {
    return a + b
}

Output

11
2

The add function may not mean much, but it delivers the idea of usage of default arguments.

Example 2 – Kotlin With Mix of Default Arguments and non-default

In the following example, we shall define a function which calculates the sum of two or three integers passed as arguments to it.

Kotlin Program – example.kt

fun main(args: Array<String>) {

    val sum1 = add(5, 6)
    val sum2 = add(5, 6, 7)
    val sum3 = add(5, 6, 7, 8)
    println(sum1)
    println(sum2)
    println(sum3)

}

/**
 * add function with two, three or four integer arguments
 * c : default argument is 0
 * d : default argument is 0
 */
fun add(a:Int, b:Int, c:Int = 0, d:Int = 0): Int {
    return a + b + c + d
}

Output

11
18
26

Observe that the parameters with default arguments are declared last in the definition.

Conclusion

In this Kotlin TutorialKotlin Default Arguments, we have learnt how to provide default argument values to parameters in function’s definition.