Skip to Content
Course content

9: Functions and Default Arguments

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 be false.
    • 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:

  1. Create a basic account using only the username.
  2. Create a verified account (change isVerified to true) but keep all other defaults. Use a named argument.
  3. Create an admin account with a "Dark" theme, providing the username, role, and theme.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.