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 ParisThis 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
MediumYou 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
1949The 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
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground