Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Check if an object implements a specific interface

Tags:

kotlin

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.

like image 500
userMod2 Avatar asked Dec 05 '19 09:12

userMod2


People also ask

How do you check if an object is an instance of an interface?

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.

How do you know if a class implements an interface?

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.

Which keyword validates whether a class implements an interface?

To declare a class that implements an interface, include an implements keyword in the class declaration.

Can Kotlin object implement interface?

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.


1 Answers

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

like image 188
Jayson Minard Avatar answered Nov 16 '22 04:11

Jayson Minard