gpt4 book ai didi

Kotlin - 有一个参数不同的辅助构造函数

转载 作者:行者123 更新时间:2023-12-02 06:31:30 25 4
gpt4 key购买 nike

我有一段 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”。​​

最佳答案

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 之前的几个参数也有默认值,除了使用 named arguments 之外,没有其他方法可以跳过它们并传递 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

关于Kotlin - 有一个参数不同的辅助构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40320920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com