Search code examples
androidkotlinparcelablekotlin-android-extensionskotlin-multiplatform

@Parcelize in multi-platform project


I'd like to create a class in a multi-platform project, and use Parcelize to make it Parcelable in the Android version.

So in my lib-common project, I tried:

expect annotation class Parcelize()
expect interface Parcelable

@Parcelize
data class Foo(x: Int): Parcelable

and in my lib-android project:

actual typealias Parcelize = kotlinx.android.parcel.Parcelize
actual typealias Parcelable = android.os.Parcelable

The first problem was that the Gradle plugin kotlin-android-extensions didn't seem to take in lib-android's build.gradle, so the package kotlinx.android.parcel was not found. I managed to work around that by just importing the library directly:

implementation "org.jetbrains.kotlin:kotlin-android-extensions-runtime:$kotlin_version"

With this, the actual definition of Parcelable compiles.

However, I am getting an error from the definition of Foo, as if it was not properly annotated with @Parcelize:

Class Foo is not abstract and does not implement abstract member public abstract fun writeToParcel(p0: Parcel!, p1: Int): Unit defined in android.os.Parcelable


Solution

  • Well that's a bit embarrassing, but I've figured out the problem was simply because I forgot to turn on the experimental features of kotlin-android-extensions, one of which is @Parcelize...

    So to get it work, it was enough to keep my expected and actual definitions of Parcelable and Parcelize as in the question, and edit lib-android's build.gradle and add the following lines:

    apply plugin: 'kotlin-android-extensions'
    androidExtensions {
        experimental = true
    }
    

    No dependencies additions are needed; that was a dead end direction.