Map java Enum to Kotlin data class

huangapple go评论80阅读模式
英文:

Map java Enum to Kotlin data class

问题

Here is the translated part:

DTO在Java中:

public class PersonDTO
{
   private Long id;
   private String name;
   private CountryCode countryCode;
}

CountryCode是一个枚举类型。

Kotlin中的数据类:

data class PersonDTO(
val id: Long? = null,
val name: String? = null,
val countryCode: String? = null //在这里如何将枚举映射为字符串..???
)

希望有所帮助。

英文:

I am making a call from service A which is in Kotlin to service B which is in Java. It return me an object which contains multiple fields. One of the fields returned in the Java object is an enum. In my kotlin code I have defined a DTO which maps the returned response to kotlin. I need to map this enum to a string value in kotlin.

DTO in Java:

public class PersonDTO
{
   private Long id;
   private String name;
   private CountryCode countryCode;
}

The CountryCode is an enum.

Data class in Kotlin:

data class PersonDTO(
val id: Long? = null,
val name: String? = null,
val countryCode: String? = null //How to map the enum to string here..???
)

Any help would be appreciated.

答案1

得分: 1

Answer to the edited question: 如何将Java枚举映射到字符串?

您可以调用枚举的name()toString()方法以获取其字符串表示形式。

name()方法无法被重写,始终返回代码中定义的值的文本表示形式,而toString()方法可以被重写,因此根据您的用例可能会选择使用哪个。由于name()方法无法被重写,我更喜欢始终使用name(),这样在与不受您控制的库一起使用时,可以减少副作用或意外行为。

英文:

Answer to the edited question: How to map a Java enum to a String?

you can call name() or toString() on an enum to get a String representation of it.

name() cannot be overwritten and always returns the textual representation of the value defined in the code, while toString() can be overwritten, so it might be depending on your use case what to use. Because of the fact that name() cannot be overwritten I prefer to always use name() wich can have less side effects or unexpected behavior when working with libraries which are not under your control.

Original Answer:

1 you don't have to do this. You can use the same Java class also in Kotlin code.

2 You could just reuse the enum, like in option 1) you can reuse the Java enum in Kotlin code:

data class PersonDTO(
    val id: Long? = null,
    val name: String? = null,
    val countryCode: CountryCode
)

3 You can write a Kotlin enum with a mapping function to create the matching instance of the enum:

enum class KotlinCountryCode {
    EXAMPLE;

    fun fromJavaCountryCode(input: CountryCode): KotlinCountryCode? {
        if (input.name() == EXAMPLE.name) {
            return EXAMPLE
        }
        return null
    }
}

huangapple
  • 本文由 发表于 2020年8月2日 23:16:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63217693.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定