我想检查SignalPayload
的子类是否实现了接口IConvertible
。我怎么能这样做?
sealed class SignalPayload {
companion object {
fun trueTypeInstance(type: KClass<SignalPayload>) : SignalPayload? {
// if (*** __ KClass<SignalPayload> implemented IConvertible ___ **)
......
}
}
}
object Empty : SignalPayload()
data class BadData(val message: String = "BAD") : SignalPayload() {
override fun toString(): String {
return message
}
}
data class payloadString(private var payload: String = "") : SignalPayload(), IConvertible
data class payloadInt(private var payload: Int = 0) : SignalPayload(), IConvertible
data class payloadFloat(private var payload: Float = 0F) : SignalPayload(), IConvertible
data class payloadBool(private var payload: Boolean = false) : SignalPayload(), IConvertible
interface IConvertible {
val asBool: Boolean
val asInt: Int
val asFloat: Float
val asString: String
fun setFromPayload(data: IConvertible)
}
我该怎么做?
UPD
我曾经想过用它
类SignalChannel
知道所需的字段mPayload
(通过属性val type: ???
)。起初mPayload
等于空
interface IArriving {
fun onNewPayload(data: SignalPayload, sender: IArriving?)
}
interface IConvertible {
val asBool: Boolean
val asInt: Int
val asFloat: Float
val asString: String
fun setFromPayload(data: IConvertible)
}
class SignalChannel(val idx: Int, val type: ???, val name: String = "") : IArriving {
var mPayload: SignalPayload = Empty
// when new data arriving - need converting for `type` and refresh field mPayload
override fun onNewPayload(data: SignalPayload, sender: IArriving?) {
if ( mPayload is Empty ) {
mPayload = SignalPayload.trueTypeInstance(type) // that's my problem
}
mPayload.setFromPayload(data)
}
}
答案 0 :(得分:1)
您可以使用正确的泛型,以便将方法限制为SignalPayload
和 IConverible
的类型:
fun <T> trueTypeInstance(): SignalPayload?
where T : IConvertible, T : SignalPayload {
TODO()
}
这样称呼:
SignalPayload.trueTypeInstance<payloadString>() //OK
SignalPayload.trueTypeInstance<Empty>() //Fails
SignalPayload.trueTypeInstance<String>() //Fails
虽然不确定您的用例......