Kotlin Default and Named Argument

Default Arguments: Kotlin provides a facility to  assign default values to function parameters. When calling a function, if not provide a value for a parameter with a default value, the default value will be used. It allows you to call the function with fewer arguments if desired.

Here’s an example of a function with default arguments:

fun greet(name: String = "Guest", message: String = "Hello") {
    println("$message, $name!")

You can call this function in multiple ways:

greet()                       // Output: Hello, Guest!
greet("John")                  // Output: Hello, John!
greet("Allen", "Hi there")     // Output: Hi there, Allen!

Named Arguments: In Kotlin, you can specify arguments by name when calling a function. This allows you to provide arguments in any order, making the function call more readable and less error-prone, especially when dealing with functions that have multiple parameters.

Using the same greet function from the previous example, let’s call it with named arguments:

greet(message = "Hi there", name = "Alice")  // Output: Hi there, Alice!

By providing the parameter names explicitly, we can change their order, making the function call more understandable and self-documenting.

Combining Default and Named Arguments: It allows you to specify only the arguments you want to change, leaving the rest to use their default values.

fun createPerson(name: String, age: Int = 30, city: String = "Unknown") {
    println("Name: $name, Age: $age, City: $city")

Calling the createPerson function with a mix of default and named arguments:

fun main(args: Array<String>){  
    createPerson("El")                            // Output: Name: El, Age: 30, City: Unknown
    createPerson("Robert", age = 25)             // Output: Name: Robert, Age: 25, City: Unknownn
    createPerson("Grey", city = "New York")      // Output: Name: Grey, Age: 30, City: New York
    createPerson("Duck", 28, "San Francisco")    // Name: Duck, Age: 28, City: San Francisco