Thanks to visit codestin.com
Credit goes to github.com

Skip to content

First Class Support for Enums #287

@eygraber

Description

@eygraber

I can see that there's limited support for enums here but this is such a huge barrier to getting started. I don't want to have to write a converter for each enum type that I use in my code.

I propose first class support for enums using the following mechanism:

This can be repeated for all the natively supported types, and should now be able to be handled internally.

interface EnumInt {
  val value: Int
}

interface EnumString {
  val value: String
}

inline fun <reified T> enumFromInt(value: Int?): T?
    where T : EnumInt, T : Enum<T> =
    value?.let { v ->
      enumValues<T>().let { values ->
        values.find {
          v == it.value
        } ?: throw IllegalArgumentException("Invalid int value: $v")
      }
    }

inline fun <reified T> enumFromString(value: String?): T?
    where T : EnumString, T : Enum<T> =
    value?.let { v ->
      enumValues<T>().let { values ->
        values.find {
          v == it.value
        } ?: throw IllegalArgumentException("Invalid string value: $v")
      }
    }

enum class Type(override val value: String) : EnumString {
      UNKNOWN("unknown"),
      IMAGE("image"),
      VIDEO("video")
}

enum class Status(override val value: Int) : EnumInt {
      ERROR(-3),
      UNRECOVERABLE_ERROR(-2),
      NONE(-1),
      DOWNLOADING(1),
      DOWNLOADED(2),
      UPLOADING(3),
      FINISHED(0)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions