如果我有 utils 方法或扩展,如何使这段代码更好?
How to make this code nicer should I have utils method or extension?
所以这个 getLocalizedTitle()
函数我有这 3 种类型的 类,我应该有 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
}
}
您可以创建一个扩展函数:
fun List<Title>.localized(locale: String): Title? =
firstOrNull { it.locale == locale }
所以这个 getLocalizedTitle()
函数我有这 3 种类型的 类,我应该有 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
}
}
您可以创建一个扩展函数:
fun List<Title>.localized(locale: String): Title? =
firstOrNull { it.locale == locale }