Hello guys. I have a question about generics. I ha...
# announcements
a
Hello guys. I have a question about generics. I have following code:
Copy code
val properties = mutableListOf<Property>()

inline fun <reified T : Property> getProperty(): T? {
    return properties.filter { it::class == T::class }.firstOrNull() as T?
}
I don't like this
as T?
part, but if i remove it i will receive error:
Copy code
Type inference failed. Required: T?, found: Property?
Am i doing something wrong?
g
You can use
.filterIsInstance<T>()
instead
❤️ 2
d
The collection's elements are Property, not T. You can try
mapNotNull { (it as? T)?.takeIf { it::class == T::class } }
1
In your particular use case, I think you should use
find { it::class == T::class } as T?
👍 1
You kinda need the
as
or
is
anyway.
Are you intentionally comparing the
::class
instead of using
is
check? The difference is subtle and probably not intended.
a
Doesn't
is
check the ability to cast to? Meaning that it will also count in inherited classes
d
Yeah
Subclasses