Dave Whyte
Dave Whyte

Reputation: 39

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)

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

Upvotes: 1

Views: 3500

Answers (2)

You could also make a simpler function (like @Ivo's function):

fun toPilotType(p: PilotTypeDTO): PilotType {
  return when(p) {
     // Add edge cases 
     // example
     PilotTypeDTO.SOME_NON_MATCHING_PILOT -> PilotType.BACKEND_VERSION_OF_THIS_PILOT
     // Those with the same name will be handled here
     else -> PilotType.valueOf(p.name)
  }
}

This way you can extend the enums without needing to update the when statement every time

Upvotes: 0

Ivo
Ivo

Reputation: 23164

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

Upvotes: 10

Related Questions