Joshua Hansen
09/13/2023, 8:08 PMvararg
constructor parameters cannot be accessed in override
methods. Here is a simple example:
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
}
}
Casey Brooks
09/13/2023, 8:13 PMvar
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)
Joshua Hansen
09/13/2023, 8:27 PMvararg
parameters as val
. Thanksephemient
09/13/2023, 8:52 PMvararg
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
class Foo(val bar1: Int, vararg bar2: String) {
val bar2: List<String> = bar2.toList()
Klitos Kyriacou
09/13/2023, 9:26 PMasList()
instead of toList()
since there's no point in copying a vararg parameter.ephemient
09/13/2023, 9:27 PMephemient
09/13/2023, 9:29 PMString[] bar2 = new String[] { "foo" };
new Foo(0, bar2);
bar2[0] = "bar";
the equivalent in Kotlin always copies the varargs array, thoughJoshua Hansen
09/13/2023, 9:31 PMval
, and instead declare a property in the class body like
val bar2NotNull = bar2.filterNotNull()