Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Parcelize annotation toghether with inheritance

I'm unable to create generic structure togother with @parcelize annotation. I want constructor to be used as construcor for Jason, Room, and Parcelable.

Lets assume we have class

@Parcelize
class Food(var taste: String = "")

Now two solution that come to my mind at first

1.complains that taste have to be var or val, to have usable Parceable constructor

@Parcelize
class FastFood(var callory:String = "", taste: String): Food(taste) // error

2.complains that I have to explicitly ovveride taste - so what are benefits from polymorphism?

@Parcelize
class FastFood(var callory: String = "", var taste: String): Food(taste) // error

How can I use efficiently inheritance together with your library?

like image 339
murt Avatar asked Jan 04 '18 14:01

murt


2 Answers

I haven't been able to find a perfect solution using @Parcelize, but there are two slightly flawed ways.

1) Make the base class abstract and only use @Parcelize in the children. This means that you can't have an instance of the parent, but sometimes that is fine. If you can afford to do this, it is an effective solution.

abstract class Food : Parcelable {
    abstract var taste: String
}

@Parcelize
class FastFood(var callory: String = "", override var taste: String = "") : Food()

2) Perhaps you need to be able to make an instance of the parent. A way to do this is to make the base class not the parent class, but rather the parent of both the parent and child classes. Unfortunately this slightly messes up the hierarchy of classes and FastFood will not be a kind of Food, but rather both will be a kind of BaseFood.

abstract class BaseFood : Parcelable {
    abstract var taste: String
}

@Parcelize
class Food(override var taste: String = "") : BaseFood()

@Parcelize
class FastFood(var callory: String = "", override var taste: String = "") : BaseFood()
like image 185
Masque Avatar answered Oct 20 '22 14:10

Masque


In Kotlin if you add to value in constructor 'val' or 'var' it becomes class property. To use Parceable you need to add it because without it Parcelable.Creator can't access it. Then you need to add 'open' modifier to Food class and to property 'taste' because in Kotlin all final by default, so you will be able to override taste value.

@Parcelize
open class Food(open val taste: String)

@Parcelize
class FastFood(var callory:String = "", override val taste: String): Food(taste)
like image 40
Onregs Avatar answered Oct 20 '22 16:10

Onregs