1

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.

3
  • Kotlin has enums too, just import it in your Kotlin code Commented Aug 2, 2020 at 15:21
  • The thing is I need to map the enum field in the response coming in to a String type in kotlin. Just edited my question. Sorry. Commented Aug 2, 2020 at 15:22
  • Use .name() on enum. Commented Aug 2, 2020 at 15:30

1 Answer 1

1

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
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry. please see the updated question. Its a String field in kotlin but the response coming in is enum.
To the downvoter: please seee my updated answer. please explain your downvote so I could understand your opinion and improve my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.