Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor call in kotlin using vararg

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]){
    }
}
like image 796
manish Avatar asked Jul 14 '15 18:07

manish


1 Answers

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.

like image 76
hotkey Avatar answered Sep 20 '22 13:09

hotkey