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
Foois not abstract and does not implement abstract memberpublic abstract fun writeToParcel(p0: Parcel!, p1: Int): Unitdefined inandroid.os.Parcelable
Parcelable. Parcelable is an Android interface that allows you to serialize a custom type by manually writing/reading its data to/from a byte array. This is usually preferred over using reflection-based serialization as it is faster to build in your serialization at compile time versus reflecting at runtime.
The first step is adding the kotlin-parcelize plugin to the shared module build. gralde file, till being able to use Parcelize annotation: As you know in regular Android projects if we want to make a class Parcelable, we should add the Parcelize annotation to it and implement the Parcelable interface.
There are 3 ways you can make your class Parcelable: Implementing the Parcelable interface and defining the serialization yourself (The traditional way) Using Android Studio plugins, like Android Parcelable code generator. Using annotation-based libraries, like Parceler.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With