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

Randomly failing to serialze external third party class

Open melvinotieno opened this issue 9 months ago • 0 comments

Describe the bug

Trying to serialize a third party class through use of the experimental serialization API @Serializer(forClass = Class::class). The trouble I am having is, most of the times this works but it would at times just randomly fail to compile even without having done any changes. The error I get is Cannot generate external serializer 'data class Example : Any': class 'com.example.Example' have constructor parameters which are not properties and therefore it is not serializable automatically

Example class is one that has been generated by a flutter tool called pigeon pub.dev and github repository

To Reproduce

An example of a class that would be generated by pigeon is

/**
 * Represents an exception that occurred during a task execution.
 *
 * Generated class from Pigeon that represents data sent in messages.
 */
data class TaskException (
  /** The error code of the exception. */
  val code: TaskErrorCode,
  /** The error message of the exception. */
  val message: String,
  /**
   * The response from the server that caused the exception. If provided, the
   * exception is considered to be as a result of a failed HTTP request.
   */
  val rawResponse: String? = null
)
 {
  companion object {
    fun fromList(pigeonVar_list: List<Any?>): TaskException {
      val code = pigeonVar_list[0] as TaskErrorCode
      val message = pigeonVar_list[1] as String
      val rawResponse = pigeonVar_list[2] as String?
      return TaskException(code, message, rawResponse)
    }
  }
  fun toList(): List<Any?> {
    return listOf(
      code,
      message,
      rawResponse,
    )
  }
}

And the following is how I use the serializer

@OptIn(ExperimentalSerializationApi::class)
@Serializer(forClass = TaskException::class)
object ExceptionSerializer : KSerializer<TaskException>

Expected behavior

Environment

  • Kotlin version: 2.0.0
  • Library version: 1.8.0
  • Kotlin platforms: JVM
  • Gradle version: 8.9
  • IDE version (if bug is related to the IDE) Android Studio 2024.2.2 Patch 2
  • Other relevant context [e.g. OS version, JRE version, ... ]

melvinotieno avatar Mar 04 '25 10:03 melvinotieno