我有一个 typescript 类,它接受任何成员名称:
interface ControlTagType {
type?: String | null;
[name: string]: any
}
class ControlTag {
tagSource: String | null = null;
tag: ControlTagType | null = null;
}
export { ControlTag };
这样我可以在 vuejs 中使用这个类,如下所示:
controlTag.push({ tagSource: 'USER', tag: { type: 'X', TAG_1: 'TAG_X' } });
controlTag.push({ tagSource: 'AUTO', tag: { type: 'Y', TAG_2: 'TAG_Y' } });
这只是我另一个问题的解决方案。
但我找不到如何在 kotlin 中实现这个通用成员:
我有一个枚举类,我在序列化时使用了它:
@JsonValue
fun value(): X {
return X( this.name : this.name)
}
如
data class X(val [name: string]: any)
我可以这样做,但它太复杂了,应该为每个类(class)做:
@JsonValue
fun value(): Any? {
when (this.name) {
XX_XX.name -> {
return object {
var XX_XX: String = name
}
}
YY_YY.name -> {
return object {
var YY_YY: String = name
}
}
ZZ_ZZ.name -> {
return object {
var ZZ_ZZ: String = name
}
}
else -> return null
}
}
同样在此实现中,它将参数名称转换为小写:
{"type":"XX","xx_XX":"XX_XX"}
最佳答案
Kotlin 中没有索引类型。
但是您可以使用基于接口(interface)的不同实现而不是 val[name: string]: any
interface ControlTagType {
val type: String?
}
data class ControlTag(
val tagSource: String? = null,
val tag: ControlTagType? = null
)
data class FirstControlTagType(
override val type: String? = null,
val firstOne: String? = null
) : ControlTagType
data class SecondControlTagType(
override val type: String? = null,
val secondOne: String? = null
) : ControlTagType
Kotlin 专为多种语言和结构而设计,例如
val[name: string]: any
比 Java 语言更动态。
关于java - Kotlin 中的任何变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61443721/