๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

Kotlin Named Arguments

A named argument is an argument written with its parameter name at a call. Naming an argument lets a call list values in a different order.

A call in parameter order

describe takes a name, an age, and a city. This call passes its values in that same order with no names.

fun describe(name: String, age: Int, city: String) {
    println("$name is $age and lives in $city")
}

fun main() {
    describe("Ana", 30, "York")
}

Names let a call change the order

Each value at this call carries its parameter name. The values sit in a new order and the printed line stays the same.

fun describe(name: String, age: Int, city: String) {
    println("$name is $age and lives in $city")
}

fun main() {
    describe(city = "York", name = "Ana", age = 30)
}

Naming makes a long call clear

ticket takes a seat, a row, and a price. The names at the call show which value fills which part.

fun ticket(seat: String, row: Int, price: Int) {
    println("$seat in row $row costs $price")
}

fun main() {
    ticket(price = 40, seat = "A3", row = 2)
}

A name the function does not have

This call adds one more named value, town, after the three real ones. describe has no parameter with that name, so the compiler stops the program with this error.

fun describe(name: String, age: Int, city: String) {
    println("$name is $age and lives in $city")
}

fun main() {
    describe(name = "Ana", age = 30, city = "York", town = "York")
}

Example

fun introduce(name: String, city: String, age: Int) {
    println("$name, $age, from $city")
}

fun main() {
    introduce("Ana", "York", 30)
    introduce(age = 30, name = "Ana", city = "York")
}

Key points

  • Write a parameter name and an = sign before the value at a call.
  • Use named arguments to make a call with many values easier to read.
  • Positional arguments are values listed in parameter order with no names.
  • A call can list named arguments in an order that differs from the definition.

In this example, introduce takes a name, a city, and an age. The first call passes its values in parameter order. The second call names each value and lists them in a new order. Both calls print the same line.

Note

A name at a call must match a parameter name in the definition.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

A function is fun box(width: Int, height: Int). Which call uses named arguments?