Kotlin-检查对象是否实现特定接口

时间:2019-12-05 09:39:35

标签: kotlin

说我有一些数据类,例如:

data class NameCreated(
    val index: Float,
    val name: String
) : ESEventPayload

然后我有了一些方法,如果<Event<out Any>>中的事件类型正在实现ESEventPayload,我想返回true。

例如:

fun isItUsing(message: AcknowledgeableMessage<Event<out Any>>): Boolean =

我希望这样的事情能够奏效,但事实并非如此:

if (ESEventPayload::class.java.isAssignableFrom(message.body.payloadType::class.java)) {
   println("It's using the interface")
} else {
   println("It isn't using")
}

我该如何在Kotlin中做到这一点?

任何帮助将不胜感激。

谢谢。

1 个答案:

答案 0 :(得分:1)

使用section = super(Child).section运算符,它看起来像:

is

这里没有理由使用if (something is ESEventPayload) { ... } 。实际上,它具有不好的铸造效果。使用isAssignableFrom时,您可以...

is

请参阅:https://kotlinlang.org/docs/reference/typecasts.html