Named arguments
- Kotlin course
- Beginner
- Lesson 75/116
- 5 min
Learn to call functions with named arguments.
Named arguments: calling by name
You can use the parameter name when calling: greet(name = "Ava", msg = "Hello"). Named arguments are not bound to order; greet(msg = "Hello", name = "Ava") gives the same result.
fun greet(name: String, msg: String = "Hi") {
println("$msg $name")
}
greet(name = "Ava", msg = "Hello") // Hello Ava
greet(msg = "Hello", name = "Ava") // Hello AvaNamed arguments are especially handy when you want to skip a required parameter in front of a default one.
Mixing positional and named arguments
You can mix positional and named arguments in a call; but positional ones must come first. After the first named argument, all the rest must be named.
fun f(a: Int, b: Int = 0, c: Int = 0)
f(1, c = 3) // a=1, b=0 (default), c=3
f(1, 2, c = 3) // a=1, b=2, c=3
// f(c = 3, 1) // error: positional after namedThis rule keeps which argument binds to which parameter unambiguous.
Practice Call greet with named arguments
Define a fun greet(name: String, msg: String = "Hello") whose body is println("$msg $name"). From main call it with named arguments: greet(name = "Ava", msg = "Hi").
Starter code
fun main() {
// Call greet with name = "Ava", msg = "Hi"
}
// Define greet: msg defaults to "Hello", body prints "$msg $name"Sample solution
fun main() {
greet(name = "Ava", msg = "Hi")
}
fun greet(name: String, msg: String = "Hello") {
println("$msg $name")
}Expected output
Hi Ava
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 fun greet(name: String, msg: String = "Hi"); what does greet(msg = "Hello", name = "Ava") print?
- Ava Hello
- Hello Ava Correct answer
- Hi Ava (due to order)
- Throws an exception
Explanation: Named arguments are not order-bound; name=Ava, msg=Hello.
2 Fill in the blank: named argument
greet(____ = "Ava", msg = "Hi")
greet(name = "Ava", msg = "Hi")
Explanation: greet(name = "Ava", msg = "Hi") is a named-argument call.
3 Match call form to outcome
| Term | Meaning |
|---|---|
greet(name = "Ava") |
Named argument |
greet("Ava") |
Positional argument |
greet(msg = "Hi") |
name comes from default |
greet(name = "Ava", msg = "Hi") |
Fully named call |
4 fun f(a: Int, b: Int = 0, c: Int = 0); what does f(1, c = 3) give?
- a=1, b=3, c=0
- Error
- a=3, b=1, c=0 Correct answer
- a=1, b=0, c=3
Explanation: a=1 (positional), c=3 (named), b=0 (default).