androidkotlinproguardandroid-r8kotlin-reflect

Data class metadata is removed with proguard / R8 for Kotlin 1.6.0


I have a package with some data classes and I'm trying to access the constructor at runtime using Kotlin reflection clazz.primaryConstructor, Everything is working as expected but when I enable R8, data classes metadata are removed so for example when I check if the KClass isData it returns false and the primary constructor is also null which happens only when enabling R8. I tried everything including adding the @keep annotation to all data classes and adding a rule to keep everything in the models package, I also added these rules

-keep class kotlin.reflect.**

-keep class kotlin.Metadata { *; }

but still no luck, any idea what is going wrong or how to fix this ?

Sample Repo

Thanks in advance.


Solution

  • What turned out to be the issue is that R8 bundeled with AGP 7.0 (release with Android Studio - Arctic Fox) does not handle Kotlin metadata correctly for Kotlin 1.6.0.

    If using Kotlin 1.6.0 (classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.0") with AGP 7.0, then R8 version 3.0.77 is required for shrinking Kotlin libraries and for using kotlin-reflect. Updating to AGP 7.0.4 is not enough, as that version is bundled with R8 3.0.76.

    To use R8 3.0.77 add the following to your settings.gradle or settings.gradle.kts:

    pluginManagement {
        buildscript {
            repositories {
                mavenCentral()
                maven {
                    url = uri("https://storage.googleapis.com/r8-releases/raw")
                }
            }
    
            dependencies {
                classpath("com.android.tools:r8:3.0.77")
                classpath('com.google.guava:guava:30.1.1-jre')
            }
        }
    }
    

    Another option for AGP 7.0 is to use Kotlin 1.5.31.

    Also consider aligning your version of kotlin-reflect with the version of the Kotlin compiler.