In Kotlin, you can use default arguments and named arguments to simplify function calls and make your code more readable and flexible. Here’s how each of them works:
Default Arguments
- Default arguments allow you to set a default value for a function parameter. If you don’t pass a value for that parameter when calling the function, the default value will be used.
- You define default values by assigning them directly in the function definition.
Example:
fun greet(name: String, greeting: String = "Hello") {
println("$greeting, $name!")
}
// Usage:
// Default value for "greeting" is used => Output: "Hello, Alice!"
greet("Alice")
// Provided value overrides the default => Output: "Hi, Bob!"
greet("Bob", "Hi")
Named Arguments
- Named arguments allow you to explicitly specify which parameter you’re setting a value for, by using the parameter name when calling the function.
- This is particularly useful when a function has many parameters, especially if some of them have default values.
Example:
fun createAccount(username: String, email: String, isAdmin: Boolean = false) {
println("Username: $username, Email: $email, Admin: $isAdmin")
}
// Usage:
// isAdmin takes the default value =>
// Output: Username: user1, Email: [email protected], Admin: false
createAccount("user1", "[email protected]")
// All arguments provided normally =>
// Output: Username: admin, Email: [email protected], Admin: true
createAccount("admin", "[email protected]", true)
// Named arguments make the order flexible =>
// Output: Username: user2, Email: [email protected], Admin: false
createAccount(email = "[email protected]", username = "user2")
Combining Default and Named Arguments
You can combine these features to make function calls more flexible:
Example:
fun printBookInfo(title: String, author: String = "Unknown", year: Int = 2023) {
println("Title: $title, Author: $author, Year: $year")
}
// Usage:
// Only title is provided; others use defaults
printBookInfo("Kotlin for Beginners")
// Output: Title: Kotlin for Beginners, Author: Unknown, Year: 2023
// Override the default value of 'year'
printBookInfo("Advanced Kotlin", year = 2020)
// Output: Title: Advanced Kotlin, Author: Unknown, Year: 2020
// Arguments in a different order with named arguments
printBookInfo(author = "John Doe", title = "My Journey")
// Output: Title: My Journey, Author: John Doe, Year: 2023
Rules and Notes:
- If a parameter has no default value, it must always be passed.
- Once you start using named arguments in a function call, all subsequent arguments should be named as well.
- Named arguments improve clarity in cases of multiple parameters with the same type or where parameter order can be confusing.
By combining default arguments and named arguments, you can create more flexible, readable, and maintainable functions in Kotlin.