
Kotlin Generics Deep Dive: Variance, Reified & Type Constraints
Kotlin Generics Deep Dive: Variance, Reified & Type Constraints Kotlin's generic system is more powerful than Java's. This guide covers variance, reified type parameters, and practical type constraints. Understanding Variance Kotlin has covariance (out) and contravariance (in): // Covariance: Producer of T interface Producer < out T > { fun produce (): T } // Contravariance: Consumer of T interface Consumer < in T > { fun consume ( item : T ) } // Invariance: Both producer and consumer (default) interface Storage < T > { fun store ( item : T ) fun retrieve (): T } Covariance allows safer type substitution: val stringProducer : Producer < String > = object : Producer < String > { override fun produce () = "Hello" } val anyProducer : Producer < Any > = stringProducer // Valid due to covariance Reified Type Parameters Reified parameters preserve type information at runtime: inline fun < reified T > parseJson ( json : String ): T { return Gson (). fromJson ( json , T :: class . java ) } da
Continue reading on Dev.to
Opens in a new tab



