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

fun multipleParams(id: Int = 1 , name: String) {
  ...
}

      

I created the above method in a class. The following method call works correctly:

multipleParams(1,"Rose")

      

Is it possible to use it in such a way that sometimes I only go through name

, and sometimes both?

multipleParams(1,"Rose")
multipleParams("Rose")

      

+3


source to share


3 answers


You are almost there - you just need to use named arguments since you already named them:

multipleParams(name = "Rose")

      



This will use the default 1

for id

as it is not passed, and use "Rose"

for name

. You cannot just use positional arguments here, because you are not supplying the first argument, so use the names you provide.

+5


source


I want to add to @ Andrew Li's answer.

You can simply change the order of the arguments to achieve this.

fun multipleParams(name: String, id: Int = 1) {
  ...
}

      



Now you can call the function like this:

multipleParams("Rose", 1)
multipleParams("Rose")

      

Note. Preferred default arguments must be at the end of the function parameters. Then you don't need to use named arguments.

+3


source


I want to add to @ chandil03's answer.

"arguments by default should be at the end of the function parameters , but other than the Function types parameter if you want to use Lambda Expression , for example:

fun multipleParams(name: String, id: Int = 1, block: () -> Unit) {
    ...
}

multipleParams("Rose") {};
multipleParams("Rose", 1) {};

      

0


source







All Articles