

The SpreadBuilder is then converted to an array when actually calling the function. In conclusion, when combining spread values into a vararg parameter, a SpreadBuilder is used behind the scenes to gather all the values. Let’s see how the corresponding decompiled Java code looks like in this case: String params = new String SpreadBuilder var10000 = new SpreadBuilder(2) var10000.addSpread(params) var10000.addSpread(opts) String allParams = (String)var10000.toArray(new String) To fix this, you need to use spread operator to unpack params array into the corresponding values: format(output, *params) It will fail with Type mismatch: inferred type is Array but String was expected compilation error.

If you try to call format function defined above like this: val params = arrayOf("param1", "param2") format(output, params) It is needed when you want to pass an array as the vararg parameter. It’s Kotlin’s spread operator - the operator that unpacks an array into the list of values from the array. “Wow!? Kotlin has pointers?” was my first reaction when I saw a Kotlin function called like this: format(output, *params). In conclusion, if vararg is not the last param it will be compiled as an array of parameter type. It gets compiled into corresponding Java code: void format(String format, String params, String encoding) When vararg parameter is not the last one in list, like this: fun format(format: String, vararg params: String, encoding: String) params) Declaring params after the vararg vararg param as the last one in listĭeclaring vararg param as the last one in list, in a Kotlin function, looks like this: fun format(format: String, vararg params: String)Īnd will be compiled into the corresponding Java code: void String format, String.

Now let’s see how the decompiled corresponding Java source code looks like when declaring vararg parameters. While in Kotlin, the vararg parameter doesn’t have to be the last one in the list, multiple vararg parameters are still prohibited. In Java, the vararg parameter has to be the last one in the parameters list - so you can only have one vararg parameter. You can do that by prefixing parameter name with the vararg modifier: fun format(format: String, vararg args: Any) vararg rules

Kotlin also supports declaring a function that can have a variable number of arguments. In this article we will start by looking at the basics about vararg and spread operator, and then explore some more elaborated scenarios - while analysing what happens behind the scenes. In some cases, you might need to define a function that should have a variable number of parameters a couple of examples that you probably have encountered in Android are the printf(String format, Obj.
