22

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

Cactus
  • 27,075
  • 9
  • 69
  • 149

2 Answers2

21

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.

Cactus
  • 27,075
  • 9
  • 69
  • 149
  • 2
    Additional, I have needed to add the dependency : implementation "org.jetbrains.kotlin:kotlin-android-extensions-runtime:$kotlin_version" – oguzhan Dec 18 '19 at 14:56
  • 1
    Your comment should be added to this answer @oguzhan ! I also needed this dependency ! – Itoun Feb 15 '20 at 01:21
6

Since Google deprecated android-kotlin-extensions plugin, you should use kotlin-parcelize plugin

apply plugin: 'kotlin-parcelize'

Source