Kotlin Default and Named Arguments, and vararg

Kotlin course · Functions · Lesson 22 of 51

Kotlin functions can have default values for their parameters, you can pass arguments by name, and a function can accept any number of values with vararg. Together, these remove the need for many overloaded versions of the same function.

Default arguments

Give a parameter a default value with =. Callers can then leave it out:

fun greet(name: String, greeting: String = "Hello") {
    println("$greeting, $name!")
}

fun main() {
    greet("Asha")              // uses the default
    greet("Ravi", "Welcome")   // overrides it
}

Output:

Hello, Asha!
Welcome, Ravi!

Named arguments

You can write the parameter name when you call a function. This makes calls easier to read, and you can pass arguments in any order:

fun createUser(name: String, age: Int, isAdmin: Boolean = false, city: String = "Unknown") {
    println("$name, $age, admin=$isAdmin, city=$city")
}

fun main() {
    createUser("Meera", 28)
    createUser("Arjun", 35, city = "Delhi")              // skip isAdmin
    createUser(age = 22, name = "Zoya", isAdmin = true)  // any order
}

Output:

Meera, 28, admin=false, city=Unknown
Arjun, 35, admin=false, city=Delhi
Zoya, 22, admin=true, city=Unknown

Named arguments are especially helpful for Boolean parameters. createUser("Arjun", 35, true) says nothing about what true means, while isAdmin = true does.

Mixing positional and named arguments

fun formatPrice(amount: Double, currency: String = "₹", decimals: Int = 2): String =
    currency + "%.${decimals}f".format(amount)

fun main() {
    println(formatPrice(1499.5))
    println(formatPrice(1499.5, decimals = 0))
    println(formatPrice(20.0, "$"))
}

Output:

₹1499.50
₹1500
$20.00

Put positional arguments first. Once you start naming arguments, it’s clearest to name the rest too.

vararg: any number of arguments

fun sum(vararg numbers: Int): Int {
    var total = 0
    for (n in numbers) total += n
    return total
}

fun main() {
    println(sum())
    println(sum(5))
    println(sum(1, 2, 3, 4))
}

Output:

0
5
10

Inside the function, numbers is an array (here an IntArray), so you can loop over it, check its size and so on.

Passing an array to vararg: the spread operator *

fun printAll(vararg words: String) {
    println(words.joinToString(" | "))
}

fun main() {
    val list = arrayOf("Kotlin", "Java", "Swift")
    printAll(*list)                 // spread the array
    printAll("Go", *list, "Rust")   // mix with normal values
}

Output:

Kotlin | Java | Swift
Go | Kotlin | Java | Swift | Rust

For a List, convert it first: printAll(*myList.toTypedArray()).

vararg with other parameters

fun log(level: String, vararg messages: String) {
    for (m in messages) println("[$level] $m")
}

fun main() {
    log("INFO", "App started", "User logged in")
}

Output:

[INFO] App started
[INFO] User logged in

A function can have only one vararg parameter. If it isn’t the last one, the parameters after it must be passed by name.

Default arguments replace overloads

In Java you might write three versions of a function. In Kotlin, one function with defaults does the job:

// Java style: three overloads
fun connect(host: String) = connect(host, 80)
fun connect(host: String, port: Int) = connect(host, port, 5000)
fun connect(host: String, port: Int, timeout: Int) { /* ... */ }

// Kotlin style: one function
fun connect(host: String, port: Int = 80, timeout: Int = 5000) { /* ... */ }

If Java code needs to call a Kotlin function with defaults, add @JvmOverloads to generate the overloads automatically.

Common mistakes

  • Mixing positional after named: createUser(name = "A", 20) doesn’t compile when the positions don’t match. Put positional arguments first.
  • Forgetting * with an array: sum(myArray) doesn’t compile. Use sum(*myArray).
  • Too many parameters: if a function needs 6+ parameters, consider passing a data class instead.

Exercise

Write a function buildUrl with a required host and optional path, port and https flag, then call it in three different ways.

fun buildUrl(host: String, path: String = "/", port: Int? = null, https: Boolean = true): String {
    val scheme = if (https) "https" else "http"
    val portPart = port?.let { ":$it" } ?: ""
    return "$scheme://$host$portPart$path"
}

fun main() {
    println(buildUrl("techpassmaster.com"))
    println(buildUrl("localhost", port = 8080, https = false))
    println(buildUrl(path = "/learn-kotlin/", host = "techpassmaster.com"))
}

Output:

https://techpassmaster.com/
http://localhost:8080/
https://techpassmaster.com/learn-kotlin/

FAQ

Does Kotlin support default parameters?

Yes. Write fun f(x: Int = 0), and callers can leave x out.

What are named arguments in Kotlin?

Passing an argument with its parameter name, like greet(name = "Asha"). It makes calls clearer and lets you skip parameters that have defaults.

What is vararg in Kotlin?

A parameter that accepts any number of values. Inside the function, it’s an array.

WhatsApp us📞 Call now