2016-10-29 15 views
3

我有科特林代码,其中所述第一和第二构造的不同微小片断,参见下文科特林 - 次要的构造,通过一个参数不同

class InstructionPrototype constructor(
     val iname: String, 
     val opcode: Int, 
     val mnemonicExample: String, 
     val numericExample: Int, 
     val description: String, 
     val format: Format, 
     val pattern: Pattern, 
     var type: Type? = null, 
     var rt: Int? = null, 
     var funct: Int? = null, 
     var conditions: Array<(n: Int) -> String?>? = null) { 
    constructor(
     iname: String, 
     opcode: Int, 
     mnemonicExample: String, 
     numericExample: Int, 
     description: String, 
     format: Format, 
     pattern: Pattern, 
     type: Type?, 
     rt: Int?, 
     funct: Int?, 
     condition: (n: Int) -> String? 
): this(iname, opcode, mnemonicExample, numericExample, description, 
     format, pattern, type, rt, funct, arrayOf(condition)) { 

    } 

是有可能通过一些语言来减少这种冗长构造?我正在考虑代数数据类型,但这并不是一个好的选择 - 它被认为是“hacky”。

回答

3

Variable number of arguments (vararg)似乎适合你的使用情况非常好,但只有当你可以放弃null作为默认值conditions因为vararg不能为空的(如使用emptyArray()):

class InstructionPrototype constructor(
     val iname: String, 
     val opcode: Int, 
     val mnemonicExample: String, 
     val numericExample: Int, 
     val description: String, 
     val format: Format, 
     val pattern: Pattern, 
     var type: Type? = null, 
     var rt: Int? = null, 
     var funct: Int? = null, 
     vararg var conditions: (n: Int) -> String? = emptyArray()) 

在使用的网站,你可以通过单一的(n: Int) -> String?,并将它打包成一个数组,并且,除了传递用逗号分隔的几个函数之外,还可以使用传播运算符传递数组:

f(vararg a: String) { } 

f("a") 
f("a", "b", "c") 

val array = arrayOf("a", "b", "c") 
f(*array) // any array of the correct type can be passed as vararg 

此外,conditions前几个参数也有缺省值,而且也没有其他办法可以跳过它们,并通过conditions比使用named arguments和传播运营商:

fun f(x: Int = 5, vararg s: String) { } 

f(5, "a", "b", "c") // correct 
f(s = "a") // correct 
f(s = "a", "b", "c") // error 
f(s = *arrayOf("a", "b", "c") // correct