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:
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:
fun join(strings: Collection<String>, delimiter: String = ", ") = strings.joinToString(delimiter)
Default values are defined by simply adding an assignment to the parameter definition. This way, you now have different ways to call this function:
fun join(strings: Collection<String>, delimiter: String = ", ") = strings.joinToString(delimiter)fun main() {val planets = listOf("Saturn", "Jupiter", "Earth", "Uranus")val joined1 = join(planets, " - ")val joined2 = join(planets)println(joined1)println(joined2)}
You’re still free to use a custom delimiter by passing in a value, but you can now omit the delimiter to simplify the function call. Think of these as ...