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...Szymon Jeziorski
02/21/2024, 9:03 PMIterable<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:
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
FYI23
02/23/2024, 3:49 AMFYI23
02/23/2024, 3:52 AM