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

To define default arguments in Kotlin, observe the following syntax :

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 – 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.

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

Example – 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.

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.