0

Is it possible to convert from int to my Enum in Kotlin? I have the Enum:

enum class Rank(val value: Int) { UNITY(1), TEN(2), HUNDRED(3), THOUSAND(4) }

And I want to call something like:

val results = ints.mapIndexed { index, element -> getRomanDigit(element, Rank(ints.size - index)) }
Galina Melnik
  • 1,947
  • 3
  • 14
  • 19
  • 4
    Does this answer your question? [How do I create an enum from a Int in Kotlin?](https://stackoverflow.com/questions/53523948/how-do-i-create-an-enum-from-a-int-in-kotlin) – Marc Sances Aug 21 '20 at 19:36

1 Answers1

1

The easiest way would be using first (it also has a firstOrNull alternative) like so:

val results = ints.mapIndexed { idx, e -> getRomanDigit(e, Rank.values().first { it.value == ints.size - idx }) }
// Or using a map for caching:
val ranks = Rank.values().map { it.value to it }.toMap()
val results = ints.mapIndexed { idx, e -> getRomanDigit(e, ranks[ints.size - idx]!!) }

This however seems like a case where you'd rather want a data class for the rank, as you cannot possibly map all possible values of ints.size - idx in enumerations:

data class Rank(val value: Int)
val results = ints.mapIndexed { idx, e -> getRomanDigit(e, Rank(ints.size - idx) }