Kotlin Named Arguments

Named arguments let you pass values to a function using the parameter name instead of relying on position. This makes function calls clearer and lets you skip optional parameters in any order.

The Problem Without Named Arguments

fun createUser(name: String, email: String, age: Int, isAdmin: Boolean) {
    println("$name | $email | $age | $isAdmin")
}

// Which argument means what? Hard to tell by reading.
createUser("Alice", "alice@mail.com", 30, true)

With Named Arguments

createUser(
    name = "Alice",
    email = "alice@mail.com",
    age = 30,
    isAdmin = true
)

Each value has a clear label. Anyone reading this code instantly knows what each value represents.

Reordering Arguments

Named arguments can appear in any order:

fun connect(host: String, port: Int, timeout: Int) {
    println("Connecting to $host:$port with timeout $timeout ms")
}

// All three orderings are valid with named arguments:
connect(host = "localhost", port = 8080, timeout = 3000)
connect(timeout = 5000, host = "api.example.com", port = 443)
connect(port = 3306, timeout = 1000, host = "db.server")

Skipping Optional Parameters

Named arguments shine when combined with default arguments. You can skip any optional parameter in the middle:

fun setupWidget(
    width: Int = 100,
    height: Int = 50,
    color: String = "blue",
    visible: Boolean = true,
    label: String = "Button"
) {
    println("Widget[$label]: ${width}x${height} | $color | visible=$visible")
}

// Only override what you need:
setupWidget(color = "red", label = "Submit")
setupWidget(width = 200, visible = false)
setupWidget(label = "Cancel", height = 30, color = "gray")

Output:

Widget[Submit]: 100x50 | red | visible=true
Widget[Button]: 200x50 | blue | visible=false
Widget[Cancel]: 100x30 | gray | visible=true

Mixing Positional and Named Arguments

You can mix positional and named arguments. Positional arguments must come first:

fun order(item: String, qty: Int, price: Double, express: Boolean = false) {
    println("$item × $qty @ ₹$price (express: $express)")
}

// First two are positional, last one is named:
order("Pen", 10, price = 5.0)
order("Notebook", 3, 45.0, express = true)

Named Arguments with Lambda Functions

fun processData(
    data: List,
    label: String = "Result",
    transform: (Int) -> Int = { it }
) {
    val result = data.map(transform)
    println("$label: $result")
}

processData(listOf(1, 2, 3, 4))
processData(data = listOf(1, 2, 3, 4), label = "Doubled") { it * 2 }
processData(data = listOf(5, 10, 15), label = "Halved", transform = { it / 5 })

Output:

Result: [1, 2, 3, 4]
Doubled: [2, 4, 6, 8]
Halved: [1, 2, 3]

Why Named Arguments Improve Code Quality


Without named args:
  scheduleTask(true, false, 3, "daily", 8)
  → What does "true" mean? What is 3? What is 8?

With named args:
  scheduleTask(
      isEnabled = true,
      sendNotification = false,
      retryCount = 3,
      frequency = "daily",
      hour = 8
  )
  → Immediately clear to any reader

Practical Example: SMS Sender

fun sendSMS(
    to: String,
    message: String,
    senderId: String = "MyApp",
    isFlash: Boolean = false,
    priority: Int = 1
) {
    println("SMS to $to")
    println("From: $senderId | Flash: $isFlash | Priority: $priority")
    println("Message: $message")
    println("───────────────────────")
}

fun main() {
    sendSMS(to = "+911234567890", message = "Your OTP is 4521")
    sendSMS(
        to = "+919876543210",
        message = "Emergency alert!",
        isFlash = true,
        priority = 5
    )
}

Leave a Comment

Your email address will not be published. Required fields are marked *