Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Parcelize in multi-platform project

Tags:

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

like image 695
Cactus Avatar asked Jul 14 '18 05:07

Cactus


People also ask

What does Parcelize do?

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.

How do you implement Parcelable in kotlin?

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.

How do I make a model class Parcelable in kotlin?

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.


1 Answers

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.

like image 177
Cactus Avatar answered Sep 19 '22 11:09

Cactus