Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I only pass one parameter to a function when it expects two?

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")
like image 758
NNikN Avatar asked Jan 04 '23 20:01

NNikN


2 Answers

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.

like image 91
Andrew Li Avatar answered Jan 07 '23 18:01

Andrew Li


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.

like image 23
chandil03 Avatar answered Jan 07 '23 18:01

chandil03