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

Ray Rahke

02/21/2024, 6:35 PM
} as T
is giving me the error
Unchecked cast: Base to T
. But this is guaranteed to be true logically...
❤️ 1
s

Szymon Jeziorski

02/21/2024, 9:03 PM
that's because
Iterable<T>.first
returns
T
. Compiler works on its return type. You can use the following approach with safe casting (
as?
) and reified generics for clean solution:
Copy code
inline fun <reified T : Base> findFirstInstance(): T = things.firstNotNullOf { it as? T }
firstNotNullOf
as the name suggest returns first not-null value of lambda transformation. Lambda transformation here uses safe cast either returning
T
or
null
, therefore resulting type of
firstNotNullOf { T? }
becomes
T
f

FYI23

02/23/2024, 3:49 AM
D