java - Kotlin 中的任何变量名

标签 java typescript variables generics kotlin

我有一个 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/

相关文章:

java - 如何在Java中使用spark ml执行多标签分类

java - 使用 REST API 将 swift 3 webservice 多次数据插入数据库

angular - 如何在Ionic中实现搜索和过滤

php - mysql_affected_rows 的 Oracle 等价物是什么?

java - 我怎样才能修改这个递归回溯算法 (NQueens) 来找到所有的解决方案而不是一个?

java - 如何在postman中将多个字符串包装成单个字符串来调用spring boot Rest API Get请求

typescript - 接口(interface) typescript 的实现

typescript - 如何在接口(interface)上扩展属性

java - 在两个 Activity 之间传递 int

mysql - MySQL UPDATE 查询中的 "intermediate"变量