如何从列表中提取参数(列表作为枚举的参数传递)?

问题描述 投票:0回答:1

我有一个名为 CarData 的枚举,它接受一个字符串作为输入。映射是在 of 函数中完成的。结果,例如,我会得到“BMW”作为汽车品牌而不是 TYPE_BMW,并且一切正常。

更改之前,它看起来像这样:

data class Car(val value: String) {

init {
   validate(value)
}


 enum class CarType {
      AUDI,
      BMW,
      FORD,
    }
enum class CarData(private val value : String) {
 TYPE_AUDI("AUDI")
 TYPE_BMW("BWM")
 TYPE_FORD("FORD")
 TYPE_DEFAULT_CAR("DEFAULT_CAR");

override fun toString(): String = value

companion object {
  fun of(type: Car?) : Car{
    if (type == null) {
      return TYPE_DEFAULT_CAR
    }
    return when(type.value) {
      "USA"-> TYPE_FORD 
      else -> valueOf(entries.first{it.value == type.value}.name)
    }
  }

我必须执行重构,现在需要接受一个列表,即 List,而不是接受 String 作为输入。几乎一切都工作正常,但我对 of 函数中的映射有问题。目前,我得到 TYPE_BMW 作为输出,并且我不确定为什么它不使用特定参数从列表中仅提取“BMW”。它应该只返回“BMW”。

这是更改后的代码:

enum class CarData(private val value : List<CarType>) {
      TYPE_AUDI(listOf(CarType.AUDI)),
      TYPE_BMW(listOf(CarType.BMW)),
      TYPE_FORD(listOf(CarType.FORD)),
      TYPE_DEFAULT_CAR(listOf());

      companion object {
        fun of(type : String) : CarData {
          val carType = CarType.entries.find {
            it.name == type
          }
          return entries.find{it.value.contain(carType)} ?: TYPE_DEFAULT_CAR
        }
      }
    }

预期输出:BWM

但是是:TYPE_BWM

有人可以指出我在哪里犯了错误,以及如何从列表中检索特定名称而不是从枚举中返回参数名称?

java spring spring-boot kotlin enums
1个回答
0
投票

这是因为您返回了一个 CarData 对象。在本例中,CarData 对象的名称为 TYPE_BMW,因此行为正确。如果您希望它返回 BMW,只需将枚举值重命名为 BMW 即可。没有其他方法可以返回 CarData 枚举对象并获得不同的结果。

您还可以将返回类型更改为 CarType,然后让您的函数类似于:

fun of(type : String) : CarType {
            val carType = CarType.entries.find {
                it.name == type
            }
            return carType?: CarType.DEFAULT_CAR_TYPE
        }

这也会返回您的期望值

© www.soinside.com 2019 - 2024. All rights reserved.