gpt4 book ai didi

android - Kotlin 数据类中的函数作为参数导致分割错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:56:14 25 4
gpt4 key购买 nike

我在 Kotlin 中有一个数据类,它使用 @Parcelize 注释来轻松打包。问题是我现在想将一个函数传递给此类,但我真的不知道如何在打包过程中不考虑该函数。

这是我的数据类:

@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 但没有成功。

这是我得到的编译错误:

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注解也不起作用。

最佳答案

只需将 lambda 转换为可序列化,然后从中创建对象

@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
)
}
}

关于android - Kotlin 数据类中的函数作为参数导致分割错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49383876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com