I want to have a data class which does this:
data class VariantModal (
val variantId: String,
val variantName: String,
val variantUnit: List<String> || variantUnitOptions
val productId: String,
val variantQuantity: Int
)
The variantUnit can either be a list of strings or a enum value,
enum class variantUnitOptions {
KG,
BUNDLE,
BOX,
PIECE
}
Since we cannot use OR like ||, I tried to use sealed class to have list of strings or enum in this way,
sealed class VariantUnit<T>(val value: T) {
class ListOfUnits(value: List<String>) : VariantUnit< List<String>>(value)
class SelectedUnit(value: variantUnitOptions) : VariantUnit<variantUnitOptions (value)
}
data class VariantModal (
val variantId: String,
val variantName: String,
val variantUnit: VariantUnit<>, //error here
val productId: String,
val variantQuantity: Int
)
But in this way, I am getting error as Type expected, I cannot give the type right now because it can either be List<String> or variantUnitOptions. How to achieve the expected behaviour? Any help is greatly appreciated.
Thanks in advance
You don't have to put generic and value to VarianUnit. Do it like that:
sealed class VariantUnit {
class ListOfUnits(val value: List<String>) : VariantUnit()
class SelectedUnit(val value: variantUnitOptions) : VariantUnit()
}
then you can use sealed class as a value:
data class VariantModal (
// other values
val variantUnit: VariantUnit,
)
and handle it as usual sealed class:
fun doSomethingWithVariantUnit(variantUnit: VariantUnit) {
when (variantUnit) {
is VariantUnit.ListOfUnits -> {
val unitsList: List<String> = variantUnit.value
// unitsList is a list, take its size for example
unitsList.size
}
is VariantUnit.SelectedUnit -> {
val unitOption: variantUnitOptions = variantUnit.value
// unitOption is an enum, take its name for example
unitOption.name
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With