Is there any difference between `is` operator and ...
# getting-started
t
Is there any difference between
is
operator and class comparison?
Copy code
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?
}
e
if there can be subclasses, then there is a difference. in this case there practically isn't as singleton objects cannot be extended
c
Yes, the
is
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-UsLlz
e
on a different note, if you wrote
Copy code
inline fun <reified T : Any> Iterable<*>.findClass(): T? =
    firstNotNullOfOrNull { it as? T }
in Kotlin 1.5+, or
Copy code
filterIsInstance<T>().firstOrNull()
in older versions, then you don't need the additional cast after finding an element
t
ahh gotcha thank you!
c
It's also worth noting that the
is
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
💯 1