https://kotlinlang.org logo
#getting-started
Title
# getting-started
t

Tim Abil

11/03/2021, 5:35 PM
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

ephemient

11/03/2021, 5:46 PM
if there can be subclasses, then there is a difference. in this case there practically isn't as singleton objects cannot be extended
c

Casey Brooks

11/03/2021, 5:48 PM
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

ephemient

11/03/2021, 5:50 PM
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

Tim Abil

11/03/2021, 6:06 PM
ahh gotcha thank you!
c

Casey Brooks

11/03/2021, 6:06 PM
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
2 Views