Daniele B
03/22/2021, 10:33 AMfun isClass(theObject : Any, theClass : KClass) : Boolean {
if (theObject is theClass) {
return true
}
return false
}
I would like to use it in this way:
val verification = isClass(myObject, Person::class)
acoconut
03/22/2021, 10:55 AMval verification = myObject is Person
Roukanken
03/22/2021, 11:10 AMinline fun <reified T> isClass(theObject: Any): Boolean {
// some other logic
return theObject is T
}
val obj: Any = "Some string"
val verification = isClass<String>(obj)
DO NOT use it if you just want to do the simple check, as the is operator is way more readable. So use this only if you need to do some additional logic, or call some additional functions...Daniele B
03/22/2021, 11:47 AMClass::class
to the function, because there is some processing I need to do with this informationRoukanken
03/22/2021, 11:48 AMT::class
Daniele B
03/22/2021, 11:49 AMKClass<*>
fun getFromAppState(theClass : KClass<*>) : Any? {
}
Daniele B
03/22/2021, 11:49 AMif (theClass.isInstance(obj)) {
...
}
kqr
03/22/2021, 11:49 AMDaniele B
03/22/2021, 11:49 AMDaniele B
03/22/2021, 11:51 AMfun isClass(theObject : Any, theClass : KClass<*>) : Boolean {
if (theClass.isInstance(theObject)) {
return true
}
return false
}
Roukanken
03/22/2021, 11:53 AMfun someOtherLogic(theClass: KClass<*>): Unit = TODO()
inline fun <reified T> isClass(theObject: Any): Boolean {
someOtherLogic(T::class)
return theObject is T
}
val obj: Any = "Some string"
val verification = isClass<String>(obj)
like this - the call, after the function is inlined would look like:
val obj: Any = "Some string"
someOtherLogic(String::class)
val verification = obj is String
Daniele B
03/22/2021, 11:56 AMRoukanken
03/22/2021, 12:00 PM::class
while calling it everywhere
b) if the type can be inferred, you don't need to specify it at all (which is probably not case here tho)Roukanken
03/22/2021, 12:02 PMfun <T> someWork(theObject: T, theClass: KClass<T>): Unit = TODO()
when you calling them you need to repeat yourself:
val x: String = "abc"
someWork(x, String::class)
Roukanken
03/22/2021, 12:03 PMinline fun <reified T> someWork(theObject: T): Unit {
someWork(theObject, T::class)
}
you can simply call it:
val x: String = "abc"
someWork(x)
Roukanken
03/22/2021, 12:03 PMsomeWork<String>(x)
automatically)Daniele B
03/22/2021, 1:54 PMKClass<*>
is very handy.Daniele B
03/22/2021, 5:58 PMKClass<T>
exists too, that is very handy, and yes, it requires “reified”