Kotlin Default Arguments

Making functions more flexible and convenient

⚙️ What are Default Arguments?

Default arguments allow functions to have preset values for parameters. When calling the function, you can skip these parameters, making functions more flexible and easier to use.


// Function with default arguments
fun greet(name: String = "World", greeting: String = "Hello") {
    println("$greeting, $name!")
}

fun main() {
    greet()                    // Uses both defaults
    greet("Alice")             // Uses default greeting
    greet("Bob", "Hi")         // Uses no defaults
}
                                    

Output:

Hello, World!

Hello, Alice!

Hi, Bob!

Default Arguments Benefits

🎯

Flexibility

Call functions with fewer arguments

fun connect(host: String = "localhost") {
    println("Connecting to $host")
}
🔧

Convenience

Avoid repetitive parameter passing

fun log(message: String, level: String = "INFO") {
    println("[$level] $message")
}
📝

Cleaner Code

Reduce function overloading

fun createUser(name: String, age: Int = 18) {
    println("User: $name, Age: $age")
}
🎨

Customization

Override defaults when needed

fun format(text: String, uppercase: Boolean = false) {
    if (uppercase) println(text.uppercase()) else println(text)
}

🔹 Basic Default Arguments

Set default values using the assignment operator (=):

fun createProfile(
    name: String,
    age: Int = 25,
    city: String = "Unknown",
    isActive: Boolean = true
) {
    println("Profile: $name, $age years old, from $city, active: $isActive")
}

fun main() {
    createProfile("Alice")                           // Uses 3 defaults
    createProfile("Bob", 30)                         // Uses 2 defaults
    createProfile("Charlie", 35, "New York")         // Uses 1 default
    createProfile("Diana", 28, "London", false)      // Uses no defaults
}

Output:

Profile: Alice, 25 years old, from Unknown, active: true

Profile: Bob, 30 years old, from Unknown, active: true

Profile: Charlie, 35 years old, from New York, active: true

Profile: Diana, 28 years old, from London, active: false

🔹 Mixed Required and Default Parameters

You can mix required and default parameters:

fun sendEmail(
    recipient: String,              // Required
    subject: String = "No Subject", // Default
    body: String = "",              // Default
    priority: String = "Normal"     // Default
) {
    println("To: $recipient")
    println("Subject: $subject")
    println("Body: $body")
    println("Priority: $priority")
    println("---")
}

fun main() {
    sendEmail("[email protected]")
    sendEmail("[email protected]", "Meeting Tomorrow")
    sendEmail("[email protected]", "Urgent", "Please call me", "High")
}

Output:

To: [email protected]

Subject: No Subject

Body:

Priority: Normal

---

To: [email protected]

Subject: Meeting Tomorrow

Body:

Priority: Normal

---

To: [email protected]

Subject: Urgent

Body: Please call me

Priority: High

---

🔹 Default Arguments with Expressions

Default values can be expressions or function calls:

import java.time.LocalDateTime

fun logMessage(
    message: String,
    timestamp: String = LocalDateTime.now().toString(),
    level: String = "INFO",
    maxLength: Int = message.length * 2
) {
    val truncated = if (message.length > maxLength) {
        message.take(maxLength) + "..."
    } else {
        message
    }
    println("[$timestamp] [$level] $truncated")
}

fun main() {
    logMessage("System started")
    Thread.sleep(1000) // Wait 1 second
    logMessage("User logged in", level = "DEBUG")
}

Output:

[2024-01-15T10:30:45.123] [INFO] System started

[2024-01-15T10:30:46.124] [DEBUG] User logged in

🧠 Test Your Knowledge

How do you specify a default value for a parameter in Kotlin?