Another powerful feature of Kotlin functions are default parameter values. These allow us to specify a default value when defining any parameter. This value will then be used if the argument is not passed to the function invocation.
To define a default argument value, add = followed by the desired value after the type component of your parameter definition:
fun helloFunctions(greeting: String, name: String = "Kotlin") {
println("$greeting $name")
}
In this example, we've made "Kotlin" the default value for the name parameter. When helloFunctions is called with both arguments, the passed argument values will be used. However, if only the greeting is passed, then the default value of "Kotlin" will be used. The following snippet shows the use of helloFunctions in two ways: one without using the default parameter value, and one that does use the default value for the name parameter:
fun main(args: Array<String>) {
helloFunctions("Hello", "Kotlin")
helloFunctions("Hello")
}
For both of these example invocations, the resultant output will be the same.
Default argument values are a powerful feature because they can remove the need for overloaded functions. If we update our function to provide a default value for greeting as well, the function can then be called with the 0, 1, or 2 argument values, depending on the desired use case. Consider the following code:
fun helloFunctions(greeting: String = "Hello", name: String = "Kotlin") {
println("$greeting $name")
}
Once all of our parameters have default values, we can invoke the function with any number of parameters, making it extremely versatile:
fun main(args: Array<String>) {
helloFunctions("Hello", "Kotlin")
helloFunctions("Hello")
helloFunctions()
}
This is especially useful when combined with named arguments. It allows us to name any argument we wish, and omit the rest as long as they have default values. In the following example, we combine named arguments and default parameter values to call helloFunctions with any combination of parameters we wish. Named arguments allow us to ignore the defined order of the parameters while default parameter values allow us to avoid passing any arguments we don't care about:
fun main(args: Array<String>) {
helloFunctions(name = "Kotlin")
helloFunctions(greeting = "Hi")
helloFunctions(name = "Android", greeting = "Hey")
helloFunctions()
}
Named arguments and default parameter values can make a function extremely flexible. They can remove the need for the Builder pattern or for overloaded methods because we can build that functionality directly into the function definition. Providing default argument values also helps self-document the code by explicitly indicating what the reasonable default values might be.
Now that we've explored the flexibility inherent within basic functions, we'll examine several different types of function variations that provide additional functionality to the language.