LEMUEL  ADANE
LEMUEL ADANE

Reputation: 8808

How to determine if an object is an inherited from a certain class in Kotlin?

In the test:

if(v is BaseModel)

will assert true if v is a direct instance of type BaseModel but will assert false if v is not a direct instance of type BaseModel but is inherited from BaseModel. Would it be nice if Kotlin has a keyword that will assert true if there is a keyword 'is from' such that the test

if(v is from BaseModel)

will assert true if v's class is inherited from BaseModel.

But how do Kotlin resolve this currently?

Upvotes: 3

Views: 5875

Answers (3)

Ali Doran
Ali Doran

Reputation: 536

In Kotlin, you are to be able to check inherited classes like this example.

open class A {}

class B : A() {}

class C {}

class M {
    fun call() {
        A()::class.isInstance(B()) //true
        A()::class.isInstance(C()) //false
    }
}

Please be careful about the turn of input classes in lines that have a comment.

Upvotes: 1

zsmb13
zsmb13

Reputation: 89528

As @Krzysztof Kozmic said, the example you gave does exactly what you're asking for. Just to give some more examples:

// Built in types
val x: Int = 25
println(x is Number) // true

// Custom types
open class A
open class B : A()
open class C : B()

println(B() is A) // true
println(C() is A) // true

Upvotes: 8

Krzysztof Kozmic
Krzysztof Kozmic

Reputation: 27374

I'm guessing what you're asking is how to determine if v directly inherits BaseModel as opposed to via an intermediate base class?

If that's the case, then this will do:

v.javaClass.superclass == BaseModel::class.java

Upvotes: 4

Related Questions