4
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") 

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

0

I want to add on to the @chandil03's answer.

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.