Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function in Kotlin data class as argument leads to parceling error

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.

This is my data class:

@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

I tried using @IgnoredOnParcel and @Transient without success.

This is the compile error I get:

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()'

And this @RawValue annotation does not work either.

like image 858
Felipe Ribeiro R. Magalhaes Avatar asked Mar 20 '18 12:03

Felipe Ribeiro R. Magalhaes


2 Answers

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
        )
    }
}
like image 90
Artur Dumchev Avatar answered Oct 31 '22 13:10

Artur Dumchev


@Parcelize
data class GearCategoryViewModel(
        val title: String,
        val imageUrl: String,
        val categoryId: Int,
        val comingSoon: Boolean,
        val onClick: @RawValue (gearCategoryViewModel: GearCategoryViewModel) -> Unit
) : DataBindingAdapter.LayoutViewModel(R.layout.gear_category_item), Parcelable

Use @RawValue with the onClick parameter.

like image 2
apurv thakkar Avatar answered Oct 31 '22 15:10

apurv thakkar