Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert an enum from another enum in Kotlin

I have an enum in the main repo:

enum class PilotType {
    REMOVABLE,
    FIXED
}

And I have another enum in another repo that is imported:

enum class PilotTypeDto {
    REMOVABLE,
    FIXED
}

In a class in my main repo I need to build this object:
(pilotType is of type PilotType)
(pilotTypeDto is of type PilotTypeDto)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

return Pilot(
    ... = ...
    pilotType = pilotTypeDto
    ... = ...
)

I need to convert pilotTypeDto to a pilotType.

I started building an extension function but it does not seem to let me create an enum:

fun pilotType(pilotTypeDto: PilotTypeDto): PilotType {
    return PilotType(
        ...                       // this does not work
    )
}

>Solution :

You can write this:

fun pilotType(pilotTypeDto: PilotTypeDto): PilotType =
    when (pilotTypeDto) {
        PilotTypeDto.REMOVABLE -> PilotType.REMOVABLE
        PilotTypeDto.FIXED -> PilotType.FIXED
    }

But as extension you could write this:

fun PilotTypeDto.toPilotType() = when (this) {
    PilotTypeDto.REMOVABLE -> PilotType.REMOVABLE
    PilotTypeDto.FIXED -> PilotType.FIXED
}

or make it part of the enum by writing this

enum class PilotTypeDto {
    REMOVABLE,
    FIXED;

    fun toPilotType() = when (this) {
        REMOVABLE -> PilotType.REMOVABLE
        FIXED -> PilotType.FIXED
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading