Search⌘ K

Default Values & Named Parameters

Explore how to make Kotlin function parameters optional by defining default values and improve code readability with named parameters. Learn to call functions flexibly without needing overloads, enhancing your ability to write cleaner Kotlin code.

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:

Kotlin
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:

Kotlin
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:

Kotlin
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 optional parameters ...