我有简单的数据类。我的意思是,它们在逻辑上是数据类,但不是 data class
,因为我需要继承和其他构造函数。它们只有字段(基本类型为 Int?
、 String?
或 List<String>?
等)和构造函数。
我需要将它们(它们的所有字段都需要传递)从 Activity 传递到 Activity,所以我需要使它们可分割(或者有更好的方法吗?)。我首先将它们创建为 data class
刚刚添加了@Parcelize
.即使有一条警告和红线写着“CREATOR”之类的东西,我也可以忽略它们,并且应用程序按预期运行。
但是,现在因为上面的原因,我把它们改成普通的类,突然出现编译错误。
Error:java.util.NoSuchElementException: Collection contains no element matching the predicate.
at org.jetbrains.kotlin.android.parcel.ParcelableCodegenExtension.getPropertiesToSerialize(ParcelableCodegenExtension.kt:374)
....too long...
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Error:Execution failed for task ':app:kaptGenerateStubsDebugKotlin'. Internal compiler error. See log for more details
我该如何解决这个问题?我应该使用 data class
?但我需要解析一个 JSON 对象来创建它们。这些类看起来像这些(不是实际的类,而是为了说明目的而简化的)。有没有比手动实现那种枯燥、笨重的可拆分代码更好的方法?
@Parcelize
open class Dog():Parcelable
{
var someField1;
var someField2;
constructor(data:JSON):this()
{
//parse data to set the fields.
}
}
@Parcelize
class Doge:Dog
{
var someField3;
var someField4;
constructor():super(); //I do not use it, but for parcellable
constructor(data:JSON):super(data)
{
//parse data to set the fields.
}
}
PS。我不得不改用 PaperParcel。它与 Kotlin 的非常相似,但它不需要主构造函数。它只要求任何构造函数都具有相同的东西,因此我可以创建一个具有与字段相同的参数名称的辅助构造函数,并且它可以工作。不过,我想知道为什么不能自动创建 CREATOR。
例如,
@PaperParcel
class Doge:Dog
{
var someField3;
var someField4;
//Needed only for PaperParcel
constructor(someField3, someField4)
{
this.someField3 = someField3;
this.someField4 = someField4;
}
companion object
{
@JvmField val CREATOR = PaperParcelDoge.CREATOR
}
//end of PaperParcel stuff.
constructor(data:JSON):super(data)
{
//parse data to set the fields.
}
}
最佳答案
如上所述 here ,你的属性应该在你的主构造函数中声明。
Parcelable support
Android Extensions plugin now includes an automatic Parcelable implementation generator. Declare the serialized properties in a primary constructor and add a @Parcelize annotation, and writeToParcel()/createFromParcel() methods will be created automatically:
@Parcelize class User(val firstName: String, val lastName: String) : Parcelable
关于android - Kotlin 的 "@Parcelize"是否适用于非数据类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48436952/