1

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

2
  • 3
    function(duration = 1800) should have worked. What error are you getting? Commented Oct 11, 2022 at 16:56
  • yes it works now, answer is updated. Thanks for the answer! Commented Oct 11, 2022 at 18:17

2 Answers 2

5

This is what you're looking for.

https://kotlinlang.org/docs/functions.html#named-arguments

Example code:

function(duration = "1800") 
Sign up to request clarification or add additional context in comments.

3 Comments

This does not work, try it in code. It throws error and asks me to add the first parameter also
I've just update my example code. So please verify it. @Kratos
Yes it works now. Good job!
1

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

3 Comments

yes I want to do skipping. With this option if I want to send f.e only last parameter, this does not help me. I still have to write all of them before coming to the last one
@Kratos Ehm, either you don't or I don't know what you mean. The (1,1... was just an illustration that it's either order or if you don't follow the order, you have to use naming.
okay now I got you. I wrongly interpreted it at first. Thank you, I gave you upvote :D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.