`} as T` is giving me the error `Unchecked cast: B...
# getting-started
r
} as T
is giving me the error
Unchecked cast: Base to T
. But this is guaranteed to be true logically...
❤️ 1
s
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
D