Kotlin / kotlinx.serialization

Kotlin multiplatform / multi-format serialization
Apache License 2.0
5.32k stars 619 forks source link

Conflict Generic Type Class with Android Jetpack Compose #1583

Open graycatdeveloper opened 3 years ago

graycatdeveloper commented 3 years ago

Environment

buildFeatures { compose true } Caused by: java.lang.AssertionError: Couldn't load KotlinClass from ...\compose-kotlin-serialization-test\app\build\tmp\kotlin-classes\debug\com\example\myapplication\GGG.class; it may happen because class doesn't have valid Kotlin annotations

If you disable compose, then GGG.class will compile successfully

Sanlorng commented 3 years ago

I also encountered the same problem, when I enabled Jetpack Compose feature

graycatdeveloper commented 3 years ago

I found a temporary solution! I created a separate module with a serialization plugin. Module my-kotlin-serialization-module build.gradle.kts:

plugins {
    id 'kotlin'
    id 'org.jetbrains.kotlin.plugin.serialization'
}
dependencies {
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.2"
}

Module my-kotlin-serialization-module Source Code:

@Serializable
data class GGG<T>(
    val data: T? = null
)
inline fun <reified T> GGG<T>.string() = Json.encodeToString(this)

Root project build.gradle.kts:

buildscript {
    dependencies {
        ...
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.10"//1.5.10 max for compose
        classpath "org.jetbrains.kotlin:kotlin-serialization:1.5.20"
        ...
    }
}

App build.gradle.kts

implementation(project(":my-kotlin-serialization-module"))

Test App:

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import com.agatgroup.api.GGG
import com.agatgroup.api.string
import com.agatgroup.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                // A surface container using the 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {
                    Text(text = "GGG: ${GGG("test").string()}!")
                }
            }
        }
    }
}

Full app: compose-kotlin-serialization-test.zip