Search⌘ K
AI Features

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 ...