Kotlin Default and Named Arguments: The Power of Flexibility 🚀
Imagine ordering a burger 🍔 at a restaurant.
- Scenario 1: You order a burger without specifying anything, and you get a default cheeseburger. 🧀🍔
- Scenario 2: You order a burger but customize it, saying "No cheese, extra lettuce, and spicy sauce." 🌶️🥬
That’s exactly how default and named arguments work in Kotlin!
- Default arguments → Provide a predefined value if no input is given.
- Named arguments → Allow you to specify values by name, in any order.
📌 In this blog, we’ll explore:
✅ Default Arguments in Kotlin ✨
✅ Named Arguments for better clarity 🏷️
✅ Combining Both for maximum flexibility 🔄
1️⃣ Default Arguments: The Smart Defaults 🎯
In Kotlin, function parameters can have default values. If a function call doesn’t provide a value, Kotlin uses the default instead!
🔹 Basic Example: Default Name
fun greet(name: String = "Guest") {
println("Hello, $name!")
}
greet() // Output: Hello, Guest!
greet("Alice") // Output: Hello, Alice!
✅ If no name is provided, it defaults to "Guest"
!
🔹 Example: Calculating Discount 🏷️
Let’s say we have a function that calculates price after a discount:
fun calculatePrice(price: Double, discount: Double = 10.0): Double {
return price - (price * discount / 100)
}
println(calculatePrice(100.0)) // Output: 90.0 (Default 10% discount)
println(calculatePrice(100.0, 20.0)) // Output: 80.0 (Custom 20% discount)
📌 If no discount is provided, it defaults to 10%
!
2️⃣ Named Arguments: Clarity and Flexibility 🏷️
With named arguments, we can specify values using their parameter names, instead of relying on the order of arguments.
🔹 Example: Named Arguments in Action 🚀
fun displayInfo(name: String, age: Int, city: String) {
println("$name is $age years old and lives in $city.")
}
// Calling with named arguments (order doesn't matter)
displayInfo(age = 30, name = "Bob", city = "New York")
📌 Output:
Bob is 30 years old and lives in New York.
✅ We changed the order, but Kotlin still understands the parameters!
3️⃣ Combining Default & Named Arguments 🔄
We can mix both default and named arguments for maximum flexibility.
🔹 Example: Customizing a Coffee Order ☕
fun orderCoffee(size: String = "Medium", sugar: Int = 2, milk: Boolean = true) {
println("Order: $size coffee with $sugar sugar(s) and ${if (milk) "milk" else "no milk"}.")
}
// Different ways to order:
orderCoffee() // Default: Medium coffee with 2 sugars and milk
orderCoffee(size = "Large") // Large coffee with default sugar and milk
orderCoffee(sugar = 1, milk = false) // Medium coffee with 1 sugar, no milk
orderCoffee(size = "Small", milk = false) // Small coffee with default sugar, no milk
📌 Output:
Order: Medium coffee with 2 sugar(s) and milk.
Order: Large coffee with 2 sugar(s) and milk.
Order: Medium coffee with 1 sugar(s) and no milk.
Order: Small coffee with 2 sugar(s) and no milk.
✅ Flexible ordering with defaults and named arguments!
4️⃣ Real-World Use Cases 🌍
🔹 Default arguments → Great for providing fallback values.
🔹 Named arguments → Useful for functions with many parameters.
📌 Example: Sending Email Notifications 📩
fun sendEmail(to: String, subject: String = "No Subject", message: String = "Hello!") {
println("Sending email to $to\nSubject: $subject\nMessage: $message\n")
}
// Sending emails with different levels of customization:
sendEmail("alice@example.com")
sendEmail("bob@example.com", "Meeting Update")
sendEmail(to = "charlie@example.com", message = "Happy Birthday!")
📌 Output:
Sending email to alice@example.com
Subject: No Subject
Message: Hello!
Sending email to bob@example.com
Subject: Meeting Update
Message: Hello!
Sending email to charlie@example.com
Subject: No Subject
Message: Happy Birthday!
✅ Flexible email sending without needing to pass all arguments every time!
🔟 Conclusion: Kotlin Gives You Superpowers! 🚀
✅ Default arguments make functions more flexible and reduce unnecessary function calls.
✅ Named arguments improve code readability and remove dependency on argument order.
✅ Combining both makes Kotlin functions powerful and customizable!
Now, go ahead and experiment with default and named arguments in your Kotlin projects! 🎯
💬 Which feature do you find most useful? Let me know in the comments! ⬇️😊