Is there any way to call a constructor using varargs without hard coding the array parameter (datain[0]
, datain[10]
, etc.). For example,
constructor(vararg datain:String): this(datain[0],datain[1],datain[2]){
}
Currently I am calling like this:
public class parent(var var1:String, var var2:String){
}
public class child(var var3:String, var1:String, var2:String): parent(var1,var2){
constructor(vararg datain:String): this(datain[0],datain[1],datain[2]){
}
}
It seems a bit meaningless since vararg
can contain more or less items than the other constructor expects. Also, it's quite a rare situation when all of the arguments have the same type so that the vararg
would suite. But no, there's currently no language feature which would decompose vararg
into function or constructor call non-vararg parameters.
I suppose, it's better for language design to make you show it explicitly that you choose certain items of vararg
as it contains no hidden pitfalls and you will always be aware of indexing.
But what you can is pass a vararg
parameter as a vararg
parameter to another function or constructor, may be, having transformed it. It's done by spread operator *
, see the example:
public class V(vararg s: String) {
constructor(vararg s: Int): this("a", *s.map(Int::toString).toTypedArray(), "b")
}
Any array of the right type can be passed using *
(including vararg
itself since it's an array), but it's what the power of vararg
ends with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With