Reputation: 8808
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
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
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
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