带别名的枚举

Enum with alias

我有一个功能需要为某些操作使用别名

例如 - count_mean 的别名是 meancountDistinct 的别名是 approxCountDistinct

"count_missing", "countMissing" -> this.countMissing.toDouble().right()
"count" -> this.count.toDouble().right()
"count_populated", "countPopulated" -> this.countPopulated.toDouble().right()
"count_distinct", "countDistinct", "approxCountDistinct" -> this.countDistinct.toDouble().right()
"count_mean", "mean" -> this.getDecimalData("mean").right() 

我想创建一个枚举 class 或其他东西来有效地分离另一个文件中的所有类型的指标。

现在我在想 Enum class

enum class FieldProfileMetrics(val value: String) { 
  CountDistinct("countDistinct", "approxDistinctCount", "count_distinct")
  .
  .
}

然后像这样使用枚举 class,这将 return 来自 Enum 的适当指标(使用别名进行检查)

val metric = FieldProfileMetrics.valueOf(metricName) 

任何有助于找出更好的结构方式的人都表示赞赏

我推荐 make aliasOf 方法。

这是示例代码。

enum class FieldProfileMetrics {
    Unknown,
    CountMissing,
    Count,
    CountPopulated,
    CountDistinct,
    CountMean;
    
    companion object {
        fun aliasOf(value: String): FieldProfileMetrics {
            return when(value) {
                "count_missing", "countMissing" -> CountMissing
                "count" -> Count
                "count_populated", "countPopulated" -> CountPopulated
                "count_distinct", "countDistinct", "approxCountDistinct" -> CountDistinct
                "count_mean", "mean" -> CountMean
                else -> Unknown
            }
        }
    }
}

并且你使用了这个方法。

val metric = FieldProfileMetrics.aliasOf(metricName)