How to Use Named Parameters in Kotlin: Simple Guide
In Kotlin, you use
named parameters by specifying the parameter name followed by an equals sign and the value when calling a function, like functionName(paramName = value). This makes your code clearer and lets you pass arguments in any order.Syntax
Named parameters let you specify the name of the argument when calling a function. This helps make your code easier to read and allows you to pass arguments in any order.
The syntax is: functionName(parameterName = value).
Each named parameter consists of the parameter's name, an equals sign, and the value you want to pass.
kotlin
fun greet(name: String, age: Int) {
println("Hello, $name! You are $age years old.")
}
greet(name = "Alice", age = 30)Output
Hello, Alice! You are 30 years old.
Example
This example shows how to use named parameters to call a function with multiple arguments. You can pass the arguments in any order by naming them.
kotlin
fun bookDetails(title: String, author: String, year: Int) {
println("Title: $title")
println("Author: $author")
println("Year: $year")
}
// Calling with named parameters in different order
bookDetails(year = 2021, title = "Kotlin Basics", author = "John Doe")Output
Title: Kotlin Basics
Author: John Doe
Year: 2021
Common Pitfalls
One common mistake is mixing positional and named arguments incorrectly. In Kotlin, all positional arguments must come before any named arguments.
Also, using named parameters with default values can help avoid passing unnecessary arguments.
kotlin
fun printInfo(name: String, age: Int, city: String = "Unknown") { println("Name: $name, Age: $age, City: $city") } // Correct usage: positional first, then named printInfo("Bob", age = 25) // Incorrect usage: named before positional (will cause error) // printInfo(age = 25, "Bob")
Output
Name: Bob, Age: 25, City: Unknown
Quick Reference
- Use
parameterName = valueto pass named parameters. - Positional arguments must come before named arguments.
- Named parameters improve readability and allow flexible argument order.
- Combine named parameters with default values to simplify calls.
Key Takeaways
Use named parameters by specifying
parameterName = value when calling functions.Named parameters let you pass arguments in any order for clearer code.
Always put positional arguments before named arguments to avoid errors.
Combine named parameters with default values to simplify function calls.
Named parameters improve code readability and reduce mistakes.