Android Kotlin create class implement Parcelable 在 'override' 的 writeToParcel 方法中报错

Android Kotlin create class implement Parcelable give an error in 'override' of writeToParcel method

为了使用 Parcelable,我遵循了 Kotlin 1.1.4 的这个版本:https://blog.jetbrains.com/kotlin/2017/08/kotlin-1-1-4-is-out/

在项目中添加这一行

androidExtensions {
    experimental = true
}

然后定义一个class :

@Parcelize
class User(val firstName: String, val lastName: String) : Parcelable

writeToParcel() 和 createFromParcel() 方法是自动创建的

override fun writeToParcel(parcel: Parcel, flags: Int) {
...
}

但 'override' 关键字和消息

仍然有错误

OVERRIDING_WRITE_TO_PARCEL_IS_NOT_ALLOWED: Overriding 'writeToParcel' is not allowed. Use 'Parceler' companion object instead

你能告诉我正确的方法吗?

编辑: 是否只有在默认构造函数中定义的属性才会添加到 Parcel,而其他的则没有?我在这个 class 中看到了这个警告。

PROPERTY_WONT_BE_SERIALIZED: Property would not be serialized into a 'Parcel'. Add '@Transient' annotation to remove the warning

确保您使用的是 kotlin 1.1.4 版本

无需覆盖 writeToParcel/createFromParcel 方法。 除非你做任何特定的 things.The studio 给你错误,但你可以忽略这个错误; lint 检查尚未更新以了解@Parcelize。相应的 YouTrack 问题在这里:

https://youtrack.jetbrains.com/issue/KT-19300

使用创建class

然后点赞

取回它

您可以安全地忽略该警告,因为它只是 lint 检查。
现在摆脱它只需使用 @SuppressLint("ParcelCreator")

例如:

@SuppressLint("ParcelCreator")
@Parcelize
class User(val firstName: String, val lastName: String) : Parcelable