Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
9: Functions and Default Arguments
How do I actually set a default value in a function?
It's much simpler than you might think. In Kotlin, you just use the assignment operator = directly in the parameter list. When you do this, you're telling the compiler: "If the caller doesn't provide a value for this specific argument, just use this one."
Let's look at a real-world scenario. Imagine we're building a notification system. Most notifications are just standard alerts, but occasionally we need to send high-priority ones or change the delivery method.
fun sendNotification(
message: String,
priority: String = "Normal",
channel: String = "Email"
) {
println("Sending $priority priority message via $channel: $message")
}
// I can call it with just the required message
sendNotification("Your order has shipped!")
// Output: Sending Normal priority message via Email: Your order has shipped!
// Or I can override just the priority
sendNotification("Server is down!", "Urgent")
// Output: Sending Urgent priority message via Email: Server is down!
This feels like method overloading. Why is this better?
If you're coming from Java or C#, your first instinct is probably to write three or four different versions of the same function—one with one argument, one with two, and so on. We call that overloading. It works, but it's a nightmare to maintain. If you add a new parameter, you have to update every single overload.
With default arguments, you write the logic once. I've found that this doesn't just save keystrokes; it makes the API much cleaner for whoever is using your code. You're providing a "sane default" that works for 80% of use cases, while still leaving the door open for the 20% of cases that need something special.
If I have a bunch of defaults, how do I change just the last one without filling in all the others?
This is where "Named Arguments" come in. If you have five parameters and you only want to change the fifth one, you can't just skip the middle three by passing null or some dummy value. Instead, you explicitly name the parameter you're targeting.
Let's expand our notification example to include a retry count and a timeout.
fun sendNotification(
message: String,
priority: String = "Normal",
channel: String = "Email",
retryCount: Int = 3,
timeoutSeconds: Int = 30
) {
// Implementation here...
}
// I only care about the message and the timeout.
// I don't want to pass "Normal", "Email", and 3 just to get to the timeout.
sendNotification(
message = "Database backup failed",
timeoutSeconds = 60
)
I highly recommend using named arguments whenever a function has more than two or three parameters. It makes your code self-documenting. When someone reads timeoutSeconds = 60, they don't have to go hunting through the function definition to figure out what that integer actually represents.
Can I put default arguments anywhere in the parameter list?
Yes, you can. However, there's a catch. If you put a parameter with a default value before one without a default value, you are practically forcing the caller to use named arguments for everything that follows.
I generally advise putting your required parameters first and your optional (defaulted) parameters last. It follows the path of least resistance for the person calling your function. If you find yourself putting defaults at the start, ask yourself if that parameter should actually be required.
📋 Practical Task
Building a Customizable User Account Creator
You are tasked with creating a function that simulates the creation of a user account in a system. The system has several settings that most users leave as default, but power users can customize.
Requirements:
- Create a function called
createAccount. - The function must take the following parameters:
username(String) - Required.role(String) - Default should be"User".isVerified(Boolean) - Default should befalse.theme(String) - Default should be"Light".
- The function should print a summary of the account created (e.g., "Account created for [username] with role [role], verified: [isVerified], theme: [theme]").
To complete the exercise, write calls to this function that demonstrate these three scenarios:
- Create a basic account using only the
username. - Create a verified account (change
isVerifiedtotrue) but keep all other defaults. Use a named argument. - Create an admin account with a "Dark" theme, providing the
username,role, andtheme.
There are no comments for now.