Default and Named Arguments
We'll cover the following
Overloading of functions is common in Java and is the way to create functions that can take different number and type of arguments. That’s an option in Kotlin as well, but the feature of default arguments is a simpler and better way to evolve functions, though it requires recompilation as it breaks binary compatibility. Also, named arguments is a great way to create readable code. We’ll focus on those two features now.
Evolving functions with default arguments
Quickly glance at the greet()
function we wrote earlier, repeated here for convenience.
fun greet(name: String): String = "Hello $name"
println(greet("Eve")) //Hello Eve
The greet()
function has a hardcoded string “Hello”, but what if we want to provide the flexibility to the caller of the function to provide a pleasantry of its choice?
If we add a new parameter to the function, then any existing code that calls the function will break because those will be shy of the much needed, albeit new, parameter. In languages like Java we use overloading for this purpose, but that may lead to code duplication. Kotlin makes this task easy with default arguments.
A default argument is a parameter that takes a default value right after the declaration. If the caller doesn’t pass a value for that parameter, then the default value is used. Specify the name of the parameter, colon, type, followed by the assignment to the default value, using =
. Let’s change the greet
method to take on an additional parameter, but with a default value.
Get hands-on with 1400+ tech skills courses.