IntelliJ compiler warning on spreading empty array for varargs

Viewed 271

I have this class that takes a a varargs parameter and a key in the primary constructor, and a secondary constructor that only requires the key, then, when calling the primary constructor, I just pass an empty Array and spread it *emptyArray<String>.

class AppendableParameter(val key: String, vararg parameters: String) {
    constructor(key: String) : this(key, *emptyArray<String>())
}

The code works fine, but IntelliJ gives me a warning:

Remove redundant spread operator

If i do remove it though, it will not work as it'd be expecting a String, and the "suggested fix" from IntelliJ just deletes the parameter, making the constructor call invalid.

Is this possibly a bug in IntelliJ's system, or am I missing something trivial?

1 Answers

I can't speak to the warning emitted by IntelliJ, but your secondary constructor is unnecessary. It's possible to call methods with a varargs parameter without passing any arguments for said varargs parameter, which is the same as passing an empty array. In other words, having:

class Foo(val key: String, vararg params: String)

Already let's you call the primary constructor like so:

val foo = Foo("key")

If you want a non-empty array to be used when no argument is given then you can specify a default argument:

class Foo(
    val key: String,
    vararg params: String = arrayOf("default", "params")
) 
Related