Explain the implications of using `*` (star projection) in Kotlin's generics, particularly in terms of type safety and flexibility.

Android interview question for Advanced practice.

Answer

Star projection () sacrifices some type safety for increased flexibility, allowing you to work with generic types without specifying exact type arguments. However, it loses the ability to access type-specific methods and properties of the underlying generic type.

Explanation

Star projection () trades type safety for flexibility. It essentially says "I don't care about the specific type argument". While this allows you to work with generic types without needing to know the exact type argument, it also means you lose the ability to call methods or access properties that depend on the specific type parameter. The compiler can't guarantee type safety in the same way as with concrete type arguments. It's a tool to use judiciously, primarily when you need greater flexibility and don't need to interact with type-specific features of the generic type.

Related Questions