因此,我对这3种类型的类拥有这个getLocalizedTitle()
函数,我应该具有utils并将标题传递给该函数,还是可以通过扩展找到更好的解决方案?
data class Carousel(val id: String, val titles: List<Title>) : ContentItem()
data class HeroBanner(val titles: List<Title>,
val descriptions: List<Description>,
val images: List<Image>, val id: String) : ContentItem()
}
data class MenuItem(val type: String, val titles: List<Title>, val actionType: String, val pageComponents: List<PageComponent>) :
fun getLocalizedTitle(locale: String): Title? {
val titles = titles.filter { it.locale == locale }
return if (titles.isNotEmpty()) {
titles[0]
} else {
null
}
}
答案 0 :(得分:1)
您可以创建扩展功能:
fun List<Title>.localized(locale: String): Title? =
firstOrNull { it.locale == locale }