5

I want some of my function parameter to be optional, so I used default parameter as follow :

fun defaultparameter(param1: String = "", param2: String = "", param3: Int = 0)

this work I can do this :

defaultparameter()
defaultparameter("titi")
defaultparameter("titi", "tata")

I can do this because default parameter are at the end but when my parameter is in the middle: defaultparameter("titi", 0) This doesn't work and it is asking me for param2.

I am guessing that the compiler can only omit parameter if there are at the end but is that normal? I understand that when parameter are the same type the compiler couldn't know which on is which but here I have a type Int at then end so I thought it would work.

My question is: default parameter only works at the end? or am I missing something? And is there any way to achieve this without using polymorphism and declaring other function with only 2 parameter: one String and one Int?

2 Answers 2

6

You can use keyword arguments:

defaultparameter("titi", param3 = 2)
0
5

According to the Kotlin Named Arguments documentation:

When you use named arguments in a function call, you can freely change the order they are listed in, and if you want to use their default values you can just leave them out altogether.

I.e. call the method as follows

defaultparameter(param1 = "titi", param3 = 0)
1
  • Thank i was missing the notion about named arguments
    – XCarb
    Commented Jun 8, 2021 at 11:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.