我有Kotlin对象
object LocalizationHelper {
var lang: String = ""
get() = MyApi.getCurrentLanguage()
fun initLanguage() {
val preferredLanguage = Locale.getDefault().language.toLowerCase()
lang = if (MyApi.setSupportedLanguage(preferredLanguage)) preferredLanguage else "en"
}
//bunch of other methods
}
有没有一种方法,如何具有相同的类,但使用
MyApi2
而没有整个LocalizationHelper
的重复代码?原因是我在主应用程序中将此类与
MyApi
一起使用,对于小部件,我需要简化的MyApi2
。但是,在90%的时间里,我将它与MyApi
一起使用。我曾想过,像
T
这样的通用对象(默认为MyApi
)会很好,但是我不确定如何或是否可以实现(注意:我主要是C++程序员,在可能的情况下)。object LocalizationHelper<T> {
var lang: String = ""
get() = T.getCurrentLanguage()
fun initLanguage() {
val preferredLanguage = Locale.getDefault().language.toLowerCase()
lang = if (T.setSupportedLanguage(preferredLanguage)) preferredLanguage else "en"
}
//bunch of other methods
}
最佳答案
您可以提取MyApi
和MyApi2
的接口(interface):
interface Api {
fun getCurrentLanguage(): String
fun setSupportedLanguage(language: String): Boolean
}
object MyApi : Api {
override fun getCurrentLanguage() = "en"
override fun setSupportedLanguage(language: String) = true
}
object MyApi2 : Api {
override fun getCurrentLanguage() = "de"
override fun setSupportedLanguage(language: String) = true
}
那么您可以将
LocalizationHelper
的常见行为移至抽象父对象:abstract class LocalizationHelperAbstract(private val api: Api) {
var lang: String = ""
get() = api.getCurrentLanguage()
fun initLanguage() {
val preferredLanguage = Locale.getDefault().language.toLowerCase()
lang = if (api.setSupportedLanguage(preferredLanguage)) preferredLanguage else "en"
}
//bunch of other methods
}
并使用适当的api实例化对象:
object LocalizationHelper : LocalizationHelperAbstract(MyApi)
object LocalizationHelper2 : LocalizationHelperAbstract(MyApi2)
关于generics - Kotlin-同一阶层,不同内部阶层,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57832340/