Generic extension function and compilation checks

Hello All,

sorry if my question was already asked but I could not find any answer.

I would like to have an extension function to extract the first element of a collection and coerce it to a specific subtype.

code
At first I had the function “oldFirstAs” but it is not good because I can pass anything as T. And I am forced to used this dirty @Suppress

Because I want compile time type safety I came with the second function “firstAs”

As you can see, the type T has an Upper Bound to X, the type of the collection. Why is the compiler letting me call with X=A and T=C, without raising an error ?

Just as a B can be provided where an A is allowed, a Collection<A> can be provided where a Collection<Any> is allowed because Collection uses an “out” type parameter. The compiler finds that X=Any and T=C, works so it uses that.

Specifying the types explicitly produces the expected error.

list.firstAs<C, A>(C::class) {
        print()
    }

Thanks for the quick answer. I wanted to avoid passing both type arguments because the syntax is pretty verbose. I hoped that the compiler could get X type to the concrete receiver list.

Oh well, in this case I don’t need the KClass parameter and then I go back to my bad method with @suppress
If you can think of a clean workaround…