'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?
Solution 1:[1]
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
Solution 2:[2]
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
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | zsmb13 |
| Solution 2 | Krzysztof Kozmic |
| Solution 3 | Ali Doran |
