Kotlin数据类中的函数作为参数导致包裹错误 [英] Function in Kotlin data class as argument leads to parceling error
问题描述
我在Kotlin帽子中有一个数据类,它正在使用@Parcelize
批注来简化打包过程.现在,我想将一个函数传递给此类,并且我真的不知道如何在打包过程中不考虑该函数.
I have a data class in Kotlin hat is using the @Parcelize
annotation for easy parcelization. Thing is I now want to pass a function to this class and I do not really know how to make the function not be considered during parceling.
这是我的数据类:
@Parcelize
data class GearCategoryViewModel(
val title: String,
val imageUrl: String,
val categoryId: Int,
val comingSoon: Boolean,
@IgnoredOnParcel val onClick: (gearCategoryViewModel: GearCategoryViewModel) -> Unit
) : DataBindingAdapter.LayoutViewModel(R.layout.gear_category_item), Parcelable
我尝试使用@IgnoredOnParcel
和@Transient
失败.
这是我得到的编译错误:
This is the compile error I get:
错误:(20,39)'Parcelize'不直接支持类型.如果希望使用'writeValue()'对参数类型进行序列化,请使用'@RawValue'注释参数类型.
Error:(20, 39) Type is not directly supported by 'Parcelize'. Annotate the parameter type with '@RawValue' if you want it to be serialized using 'writeValue()'
并且此@RawValue
注释也不起作用.
And this @RawValue
annotation does not work either.
推荐答案
只需将lambda转换为可序列化的对象,然后从
Just cast lambda to serializable, and then create object from
@Parcelize
data class GearCategoryViewModel(
val title: String,
val imageUrl: String,
val categoryId: Int,
val comingSoon: Boolean,
@IgnoredOnParcel val onClick: Serializable
) : DataBindingAdapter.LayoutViewModel(R.layout.gear_category_item), Parcelable {
fun onClicked() = onClick as (gearCategoryViewModel: GearCategoryViewModel) -> Unit
companion object {
fun create(
title: String,
imageUrl: String,
categoryId: Int,
comingSoon: Boolean,
onClick: (gearCategoryViewModel: GearCategoryViewModel) -> Unit
): GearCategoryViewModel = GearCategoryViewModel(
title,
imageUrl,
categoryId,
comingSoon,
onClick as Serializable
)
}
}
这篇关于Kotlin数据类中的函数作为参数导致包裹错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!