Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have multiple types for a variable in a data class in kotlin

Tags:

kotlin

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

like image 840
Chaitra D Avatar asked Nov 01 '25 23:11

Chaitra D


1 Answers

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
        }
    }
}
like image 200
G.Domozhirov Avatar answered Nov 04 '25 02:11

G.Domozhirov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!