0
0
Kotlinprogramming~5 mins

Named arguments for clarity in Kotlin

Choose your learning style9 modes available
Introduction

Named arguments help make your code easier to read by showing what each value means.

When a function has many parameters and you want to avoid confusion.
When you want to skip some optional parameters and only set specific ones.
When you want your code to be self-explanatory without extra comments.
When calling functions with parameters of the same type to avoid mixing values.
When you want to improve code readability for others or your future self.
Syntax
Kotlin
fun functionName(param1: Type1, param2: Type2) {
    // function body
}

functionName(param1 = value1, param2 = value2)

You write the parameter name, then an equals sign, then the value.

Order of named arguments can be changed for clarity.

Examples
Using named arguments to clearly show which value is for which parameter.
Kotlin
fun greet(name: String, age: Int) {
    println("Hello, $name! You are $age years old.")
}

greet(name = "Alice", age = 30)
Named arguments let you change the order without confusion.
Kotlin
greet(age = 30, name = "Alice")
Skipping the email parameter by naming only the ones you want to set.
Kotlin
fun createUser(name: String, email: String = "", age: Int = 0) {
    println("User: $name, Email: $email, Age: $age")
}

createUser(name = "Bob", age = 25)
Sample Program

This program prints book details using named arguments in a different order for clarity.

Kotlin
fun bookDetails(title: String, author: String, year: Int) {
    println("Title: $title")
    println("Author: $author")
    println("Year: $year")
}

fun main() {
    bookDetails(author = "George Orwell", title = "1984", year = 1949)
}
OutputSuccess
Important Notes

Named arguments improve readability but are optional.

Do not mix named and positional arguments after the first named argument.

Using named arguments can help avoid mistakes when calling functions with many parameters.

Summary

Named arguments show which value goes to which parameter.

They let you change the order of arguments for clarity.

They help skip optional parameters easily.