So I have this function that has 8 optional parameters (yes I know it's bad practice to have that much, this is legacy code :D).
It goes something like this:
private fun function(
rightImage: Int = 0,
background: Int = R.drawable.account_item_bg,
leftImage: Int = 0,
translation: String? = null,
name: String? = null,
age: String? = null,
length: String? = null,
duration: String? = null)
Now in my code, I want to call this function and give it only the last parameter (duration). I don't care for other ones.
But at the moment to call this, I Would do it like this:
function(0, R.drawable.account_item_bg, 0, null, null, null, null, 1800)
I was just thinking in the moment of writing this code that it would be cool to have option to send only parameters at the particular place (f.e parameter 6, or last parameter), and not repeat all the optional ones.
Is there maybe option like this, does anyone know? Thanks
CodePudding user response:
This is what you're looking for.
https://kotlinlang.org/docs/functions.html#named-arguments
Example code:
function(duration = "1800")
CodePudding user response:
You can do it by specifying the argument name.
e.g. function(1, 1, duration = "")
You don't necessarily have to do it for every argument but if you skip some then yes