Hi, I've found this limitation just recently and w...
# getting-started
j
Hi, I've found this limitation just recently and was wondering if this is a known issue, or if it is expected to not work. It seems that
vararg
constructor parameters cannot be accessed in
override
methods. Here is a simple example:
Copy code
fun main() {
    val foo = Foo(1, "Hello", "World")
    foo.doIt()
}

interface DoSomething {
    fun doIt()
}

class Foo(val bar1: Int, vararg bar2: String) : DoSomething {
    override fun doIt() {
        println(bar1)
        println(bar2) // Unresolved Reference: bar2
    }
}
c
You still need to mark a vararg parameter as
var
or
val
. Otherwise, it’s simply a value passed into the constructor, but not set to an actual class property. Try
class Foo(val bar1: Int, vararg val bar2: String)
j
Ahh yeah that worked. I didn't know you could mark
vararg
parameters as
val
. Thanks
e
vararg
is
Array
but
List
is a better data structure in most cases. unless there are other reasons to keep the
Array
around, I would write
Copy code
class Foo(val bar1: Int, vararg bar2: String) {
    val bar2: List<String> = bar2.toList()
1
k
Perhaps
asList()
instead of
toList()
since there's no point in copying a vararg parameter.
e
well, it depends. if the caller is Java, they can hold onto and mutate the array after making the call
e.g. in Java this mutates the incoming parameter
Copy code
String[] bar2 = new String[] { "foo" };
new Foo(0, bar2);
bar2[0] = "bar";
the equivalent in Kotlin always copies the varargs array, though
👍 1
j
In my case, the vararg param is nullable. So I opted to not mark it with
val
, and instead declare a property in the class body like
val bar2NotNull = bar2.filterNotNull()