kotlinx.serialization icon indicating copy to clipboard operation
kotlinx.serialization copied to clipboard

Cannot generate external serializer: class is defined in another module

Open nvkleban opened this issue 2 years ago • 7 comments

Describe the bug Can't generate external serializer for a 3rd party Kotlin class in Android project. 3rd party class is like by definition class from "another module" why I can't serialize it that way?

Simplified example for problem:

I have Example class in :mylibrary module

data class Example(val name: String)

In :app module I try to encode it

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val example = Example("test")
        val text = Json.encodeToString(ExampleSerializer, example)
    }
}

@OptIn(ExperimentalSerializationApi::class)
@Serializer(forClass = Example::class)
object ExampleSerializer

Output: Error: Cannot generate external serializer 'ExampleSerializer': class 'Example' is defined in another module

To Reproduce serialization.zip

Expected behavior External serializer generated succesfully

Environment

  • Kotlin version: 1.9.20
  • Library version: plugin:1.9.20, json:1.6.1
  • Kotlin platforms: JVM
  • Gradle version: 8.4
  • IDE version: Android Studio Giraffe | 2022.3.1 Patch 4
  • Other relevant context: Mac OS, M1

nvkleban avatar Nov 21 '23 20:11 nvkleban

@nvkleban Did you ever get the solution to this or at least the cause?

melvinotieno avatar Dec 30 '24 20:12 melvinotieno

@melvinotieno unfortunately no, we just don't use this approach, still waiting this to be fixed though

nvkleban avatar Jan 02 '25 13:01 nvkleban

@nvkleban, which solution did you end up using?

melvinotieno avatar Jan 02 '25 13:01 melvinotieno

@melvinotieno we just don't use this feature

nvkleban avatar Jan 03 '25 15:01 nvkleban

Is there really any technical restriction why this shouldn't be working? The limitation seems to be quite arbitrary...

sschuberth avatar Apr 11 '25 09:04 sschuberth

Is there really any technical restriction why this shouldn't be working? The limitation seems to be quite arbitrary...

This is technical limitation due to the features of the compiler. Each module is compiled independently of each other. At most, there is access to the bytecode and Kotlin metadata of the dependency, but this is not enough to create a correct serializer (for example, to get the default values)

shanshin avatar Apr 11 '25 09:04 shanshin

but this is not enough to create a correct serializer (for example, to get the default values)

I see, thanks.

sschuberth avatar Apr 11 '25 09:04 sschuberth