Home > Software engineering >  How to convert an enum from another enum in Kotlin
How to convert an enum from another enum in Kotlin

Time:11-12

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)

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
    )
}

CodePudding user response:

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
    }
}
  • Related