Say I have some data class like:
data class NameCreated(
val index: Float,
val name: String
) : ESEventPayload
I then have some method where I want to return true if the Event's type in <Event<out Any>>
is implementing ESEventPayload
.
So for example:
fun isItUsing(message: AcknowledgeableMessage<Event<out Any>>): Boolean =
I was hoping something like this would work, but it's not:
if (ESEventPayload::class.java.isAssignableFrom(message.body.payloadType::class.java)) {
println("It's using the interface")
} else {
println("It isn't using")
}
How do I go about doing this in Kotlin?
Any help would be appreciated.
Thanks.
The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.
A class implements an interface if it declares the interface in its implements clause, and provides method bodies for all of the interface's methods. So one way to define an abstract data type in Java is as an interface, with its implementation as a class implementing that interface.
To declare a class that implements an interface, include an implements keyword in the class declaration.
Android Dependency Injection using Dagger with Kotlin In Kotlin, the interface works exactly similar to Java 8, which means they can contain method implementation as well as abstract methods declaration. An interface can be implemented by a class in order to use its defined functionality.
Use the is
operator, which simply looks like:
if (something is ESEventPayload) { ... }
There is no reason here to use isAssignableFrom
. In fact it has the negative consequence of not smart casting. When using is
you can...
if (something is ESEventPayload) {
// something here is now smart cast as ESEventPayload, no casting needed
println(something.eventPayloadMemberOrMethod)
}
See: https://kotlinlang.org/docs/reference/typecasts.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With