Menu
Coddy logo textTech

Named Arguments

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 58 of 93.

When calling a function with multiple parameters, you normally pass arguments in the exact order they're defined. But Kotlin offers a cleaner alternative: named arguments.

With named arguments, you specify which parameter each value belongs to by using the parameter name followed by =:

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

fun main() {
    createProfile(name = "Alice", age = 25, city = "Paris")
}
// Output: Alice, 25, from Paris

This makes your code more readable, especially when a function has several parameters of the same type. Compare these two calls:

// Without named arguments - what do these numbers mean?
calculateArea(10, 5, 3)

// With named arguments - much clearer!
calculateArea(length = 10, width = 5, height = 3)

Named arguments also let you pass values in any order you prefer:

fun greet(firstName: String, lastName: String) {
    println("Hello, $firstName $lastName!")
}

fun main() {
    greet(lastName = "Smith", firstName = "John")
}
// Output: Hello, John Smith!

You can mix positional and named arguments, but once you use a named argument, all following arguments should also be named to avoid confusion.

challenge icon

Challenge

Medium

You are provided with the following function:

fun formatBook(title: String, author: String, year: Int) {
    println("\"$title\" by $author ($year)")
}

Read three inputs: a book title (String), an author name (String), and a publication year (Int).

Call the formatBook function using named arguments in this specific order: year, title, author.

For example, if the inputs are:

1984
George Orwell
1949

The output should be:

"1984" by George Orwell (1949)

Try it yourself

fun formatBook(title: String, author: String, year: Int) {
    println("\"$title\" by $author ($year)")
}

fun main() {
    val title = readLine()!!
    val author = readLine()!!
    val year = readLine()!!.toInt()
    
    // TODO: Call formatBook using named arguments in this order: year, title, author
    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground