1

If I try to type:

enum class EGraphicsAPIConvention(@get:JvmName("i") val i: Int) {    
   API_DirectX(0),    
   API_OpenGL(1)    
}

fun EGraphicsAPIConvention.of(i: Int) = values().first { it.i == i }

The compiler complains:

unresolved reference values

this.values() doesn't help neither

Why don't I have values() available?

Cœur
  • 37,241
  • 25
  • 195
  • 267
elect
  • 6,765
  • 10
  • 53
  • 119

1 Answers1

4

The fun EGraphicsAPIConvention.of(i: Int) is adding an extension method to all EGraphicsAPIConvention instances so that you can write EGraphicsAPIConvention. API_DirectX.of(1).

Kotlin currently does not provide a way to write an extension function at a class level.

However you can make use of companion object to get the desired behavior like so:

enum class EGraphicsAPIConvention(@get:JvmName("i") val i: Int) {
    API_DirectX(0),
    API_OpenGL(1);

    companion object {
        fun of(i: Int) = values().first { it.i == i }
    }
}

And then use it: EGraphicsAPIConvention.of(0)

miensol
  • 39,733
  • 7
  • 116
  • 112