Kotlin – 次要构造函数,由一个参数不同

我有一段Kotlin代码,其中第一个和第二个构造函数细微不同,请参见下文

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”。

可变数量的参数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? ,它将被打包成一个数组,除了传递用逗号分隔的几个函数之外,还可以使用spread运算符传递一个数组:

 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

 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 
Interesting Posts