Tim Abil
11/03/2021, 5:35 PMis
operator and class comparison?
sealed class MyClass {
object ONE : MyClass()
object TWO : MyClass()
}
inline fun <reified T> List<MyClass>.findClass(): T? {
return find { it is T } as T
}
fun <T: Any> List<MyClass>.findClass(clazz: KClass<T>): T? {
return find { it::class == clazz } as T?
}
ephemient
11/03/2021, 5:46 PMCasey Brooks
11/03/2021, 5:48 PMis
operator will check the entire class hierarchy to see if any superclasses/interfaces of an object is the T
type (bascally, whether you can cast the object to T without throwing a ClassCastException).
Checking the class through ==
will only check the object's own class type.
This example might help you see the difference https://pl.kotl.in/Rrr-UsLlzephemient
11/03/2021, 5:50 PMinline fun <reified T : Any> Iterable<*>.findClass(): T? =
firstNotNullOfOrNull { it as? T }
in Kotlin 1.5+, or
filterIsInstance<T>().firstOrNull()
in older versions, then you don't need the additional cast after finding an elementTim Abil
11/03/2021, 6:06 PMCasey Brooks
11/03/2021, 6:06 PMis
operator can be a relatively expensive check, especially if the class hierarchy is large. The ==
check is basically going to be a simple object identity check (===
) since Class objects are singletons, which is very quick