Default Values & Named Parameters
Discover how to use default parameter values to increase the flexibility of your functions and how to call functions using named parameters.
We'll cover the following...
In Kotlin, you can define default values for function parameters to make them optional.
Default Parameter Values #
Let’s say you have a function that joins a collection of strings into a single string:
Press + to interact
fun join(strings: Collection<String>, delimiter: String) = strings.joinToString(delimiter)
For instance, join(listOf("Kotlin", "Java"), " > ")
would return "Kotlin > Java"
.
With this function definition, you always have to pass in a delimiter
. But most commonly, you’ll want to have a comma as delimiter, so it makes sense to set this as the default value:
Press + to interact
fun join(strings: Collection<String>, delimiter: String = ", ") = strings.joinToString(delimiter)
Default values are defined by simply adding an assignment to the ...
Access this course and 1400+ top-rated courses and projects.