Search⌘ K
AI Features

Arguments

Explore how default and named arguments in Kotlin allow you to write more concise and readable functions. This lesson helps you understand setting default parameter values, using named arguments for clarity, and combining these features to minimize code duplication and improve maintainability.

Default arguments

Kotlin allows us to provide function parameters with a default value, which is used if the corresponding argument is omitted on the call.

fun String.splitString(separator: Char = ',')

When splitting a string with the extension function above (more on extension functions later), we can choose any separator. However, thanks to the default value “,” we can also omit it, if the “,” is actually what we need:

Kotlin 1.5
// definition of extension function splitString not shown.
fun main() {
var header : String = "Column 1 | Column 2 | Column3 "
var names : String = "Apples, Oranges, Bananas"
val list = header.splitString('|') // splits header on |
val list1 = names.splitString() // splits names on ,
println(list)
println(list1)
}
str.split('|') // splits str on
...