Reputation: 937
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
?
Upvotes: 5
Views: 2926
Reputation: 19949
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)
Upvotes: 5