Kotlin

Default Arguments + Named Parameters

admin by @admin ADMIN
4m ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Default values eliminate most overload sets. Named args make call sites self-documenting and let you skip middle parameters without thinking about positions.
Kotlin
Raw
fun createRequest(
    url: String,
    method: String = "GET",
    timeoutMs: Int = 30_000,
    followRedirects: Boolean = true,
    userAgent: String = "myapp/1.0",
) {
    println("$method $url (timeout=${timeoutMs}ms)")
}

fun main() {
    // Positional — easy when there's only one or two args
    createRequest("https://example.com")
    createRequest("https://example.com", "POST")

    // Named — skip middle defaults, document call site
    createRequest(
        url             = "https://api.example.com",
        timeoutMs       = 5_000,
        followRedirects = false,
    )

    // Mix positional + named: positionals first, then named
    createRequest("https://example.com", timeoutMs = 1_000)

    // Java callers don't get named args — use @JvmOverloads if needed:
    // @JvmOverloads fun createRequest(url: String, method: String = "GET", ...)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.