具有所需接口的通用枚举类型参数

Generic Enum type parameter with required interface

我的界面如下所示:

interface LabelledEnum {
    fun getLabelId(): Int
}

我在枚举中继承了这个接口class如下:

enum class Period : LabelledEnum {
    YTD {
        override fun getLabelId(): Int =
            R.string.ytd_label
    },
    ONE_MONTH {
        override fun getLabelId(): Int =
            R.string.1m_label
    },
    THREE_MONTHS {
        override fun getLabelId(): Int =
            R.string.3m_label
    },
    SIX_MONTHS {
        override fun getLabelId(): Int =
            R.string.6m_label
    },
    ONE_YEAR {
        override fun getLabelId(): Int =
            R.string.1y_label
    },
    THREE_YEARS {
        override fun getLabelId(): Int =
            R.string.3y_label
    },
    FIVE_YEARS {
        override fun getLabelId(): Int =
            R.string.5y_label
    },
    MAX {
        override fun getLabelId(): Int =
            R.string.max_label
    };
}

我有一个自定义可组合项,我正在处理我想要使其通用的地方(使用类型参数而不是硬编码),但我正在努力寻找一种方法来实现此通用类型参数,以便类型参数是必然是一个继承我的接口的枚举 LabelledEnum.

到目前为止,我的可组合项看起来像这样:

@Composable
inline fun <reified T : Enum<T>> CustomTabRow(
    selectedEnum: T,
    crossinline onEnumSelected: (T) -> Unit,
    modifier: Modifier = Modifier,
) {
    // Things happen here
}

有没有办法确保类型参数 T 是一个 Enum 并且继承自 LabelledEnum

如果不行,我会使用一种解决方法,但如果可能的话,我真的更愿意让它工作

Kotlin 有这样的 where syntax to express constraints

@Composable
inline fun <reified T> CustomTabRow(
    selectedEnum: T,
    crossinline onEnumSelected: (T) -> Unit,
    modifier: Modifier = Modifier,
) where T : Enum<T>, T : LabelledEnum  {
    // Things happen here
}

请注意,您必须将 T : Enum<T> 移至 where 子句。