我的代码中有一个场景,我希望一个类为两种不同的类型实现一个接口,比如下面的示例:
interface Speaker<T> {
fun talk(value: T)
}
class Multilinguist : Speaker<String>, Speaker<Float> {
override fun talk(value: String) {
println("greetings")
}
override fun talk(value: Float) {
// Do something fun like transmit it along a serial port
}
}
Kotlin is not pleased with this, citing:
Type parameter T of 'Speaker' has inconsistent values: kotlin.String, kotlin.Float
A supertype appears twice
我知道一个可能的解决方案是实现以下代码,其中我用<Any>
实现接口,然后自己判断类型并将它们委托给它们的函数.
interface Speaker<T> {
fun talk(value: T)
}
class Multilinguist : Speaker<Any> {
override fun talk(value: Any) {
when (value) {
is String ->
internalTalk(value)
is Float ->
internalTalk(value)
}
}
fun internalTalk(value: String) {
println(value)
}
fun internalTalk(value: Float) {
// Do something fun like transmit it along a serial port
}
}
However, that feels like I'm removing type safety and communication about what the class is used for, and is asking for trouble down the line. Is there a better way to implement this in Kotlin? Additionally - what's the reasoning behind it not being allowed the way I indicated in the first sample? Aren't interfaces just a contract of signatures I'm required to implement, or is there something I'm missing involving generics here?