Any idea how to check if a `T` is an Enum? I’m rea...
# javascript
v
Any idea how to check if a
T
is an Enum? I’m really afraid to write code like
T::class.js.toString().contains("Enum.call(this")
, although this works for the legacy compiler (
Enum.call(this);
) and for the IR compiler (
Enum.call(this, name, ordinal);
) Question on StackOverflow
t
Why do you need such check?
v
to properly deserialize a response from Ktor to the corresponding type (e.g. String, Enum, Class). Ktor/kotlinx-serialization can’t do this right now (runtime error with exception)
a
Strange. I am extensively using serialization with JS/IR and a bunch of Enums without problem. Whats your use case?
t
I also use enum serialization - no problems detected
v
consider the following code:
Copy code
enum class EnumValue { OK, FAIL }

fun main() {

  val client = HttpClient {
    install(JsonFeature) {
      serializer = KotlinxSerializer()
    }
  }

  GlobalScope.launch {
    console.log(client.get<EnumValue>("<https://enhfqc4t7bqezvq.m.pipedream.net>"))
  }
}
it fails with
Copy code
"NoTransformationFoundException: No transformation found: class ByteChannelJS -> class EnumValue
with response from <https://enhfqc4t7bqezvq.m.pipedream.net/>:
status: 200 
response headers: 
content-length: 2
, content-type: text/html; charset=utf-8

    at Object.captureStack (webpack-internal:///./kotlin-dce-dev/kotlin.js:38592:15)
    at NoTransformationFoundException.Exception [as constructor] (webpack-internal:///./kotlin-dce-dev/kotlin.js:38925:14)
    at NoTransformationFoundException.RuntimeException [as constructor] (webpack-internal:///./kotlin-dce-dev/kotlin.js:38951:17)
    at NoTransformationFoundException.UnsupportedOperationException [as constructor] (webpack-internal:///./kotlin-dce-dev/kotlin.js:39041:24)
    at UnsupportedOperationException_init (webpack-internal:///./kotlin-dce-dev/kotlin.js:39047:37)
    at new NoTransformationFoundException (webpack-internal:///./kotlin-dce-dev/ktor-ktor-client-core-js-legacy.js:1243:5)
    at Coroutine$receive_qi9ur9$.doResume (webpack-internal:///./kotlin-dce-dev/ktor-ktor-client-core-js-legacy.js:912:17)
    at HttpClientCall_0.receive_qi9ur9$ (webpack-internal:///./kotlin-dce-dev/ktor-ktor-client-core-js-legacy.js:949:21)
    at Coroutine$main$lambda.doResume (webpack-internal:///./kotlin-dce-dev/untitled.js:160:36)
    at Coroutine$execute_s9rlw$.CoroutineImpl.resumeWith_tl1gpc$ (webpack-internal:///./kotlin-dce-dev/kotlin.js:38763:35)"
t
EnumValue
must have
@Serializable
annotation in your example
v
Doesn’t change anything for me
(also applied of course the serialization plugin)
t
Copy code
@Serializable
enum class EnumValue { 
    @SerialId("OK") OK, 
    @SerialId("FAIL") FAIL,

    ;
}
v
where do you find the @SerialId annotation?
Note that with
Copy code
@SerialName("OK") OK,
it fails with the same exception
but also, the original question was not how to handle this in ktor, but rather how to detect if a generic type is an Enum 🙂
e