Kotlinx.serialization: Calling ::class.serializer() not working for a local class (Kotlin/JS)

Created on 22 Apr 2018  路  2Comments  路  Source: Kotlin/kotlinx.serialization

For a local class MyData (declared within a block) you can't get a serializer instance by calling MyData::class.serializer(). But the expression MyData.serializer() works fine.
For a top level or nested classes both forms are working ok.
This error makes all inline functions with reified type parameters unusable for such classes (for instance JSON.stringify()).

Platform: Kotlin/JS 1.2.40
Kotlin serialization: 0.4.2

design

Most helpful comment

Root of this issue is quite interesting. Serialization plugin adds a companion object for each serializable class to access serializer functions and for internal machinery. But in Kotlin language, companion objects in local classes are prohibited. While JVM compiler works well with such synthetic declarations, JS compiler perform some optimisations and doesn't define Companion property on local KClass, while direct companion access (MyData.serializer()) still works.

I'll investigate further to see if it's possible to disable this optimisation for synthetic declarations.

All 2 comments

Root of this issue is quite interesting. Serialization plugin adds a companion object for each serializable class to access serializer functions and for internal machinery. But in Kotlin language, companion objects in local classes are prohibited. While JVM compiler works well with such synthetic declarations, JS compiler perform some optimisations and doesn't define Companion property on local KClass, while direct companion access (MyData.serializer()) still works.

I'll investigate further to see if it's possible to disable this optimisation for synthetic declarations.

We've decided not to implement this during the transition between old JS compiler backend to new JS IR backend.
Now all inline reified functions are using typeOf API instead of KClass, so the problem should be gone for most of the usages.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

raderio picture raderio  路  3Comments

elizarov picture elizarov  路  3Comments

Egorand picture Egorand  路  3Comments

just-kip picture just-kip  路  3Comments

kastork picture kastork  路  3Comments