2016-10-29 121 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