fun multipleParams(id: Int = 1 , name: String) {
...
}
I created the above method in the class. The following method call is a working correctly with:
multipleParams(1,"Rose")
Is it possible to use it in a way, such that sometimes I pass only name
and sometimes both?
multipleParams(1,"Rose")
multipleParams("Rose")
You're almost there -- you just need to utilize named arguments since you've already have them named:
multipleParams(name = "Rose")
This will use the default value of 1
for id
as it is not passed and use "Rose"
for name
. You can't simply use positional arguments here because you're not supplying the first argument, so use the names you've given.
I want to add on to the answer of @Andrew Li.
You can just change the order of arguments to achieve that.
fun multipleParams(name: String, id: Int = 1) {
...
}
Now you can call function following way:
multipleParams("Rose", 1)
multipleParams("Rose")
Note: Preferably default arguments should be at the end of function parameters. Then you need not use named arguments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With