Skip to main content
Definition Website Computer and Technology

Generics

Subject: Computer and Technology noun /dʒəˈnɛr.ɪks/ 1 definition

  1. Definition (noun)

    Entry #267 · Updated

    Generics are a programming language feature implementing parametric polymorphism that enables functions, classes, interfaces, and data structures to be written with placeholder type parameters instead of fixed concrete types. At instantiation or call sites, concrete type arguments substitute for these parameters—either explicitly or through type inference—allowing compilers to verify type consistency across reusable containers, algorithms, and APIs without duplicating source code. Languages commonly pair type parameters with constraint bounds and variance rules to restrict permissible substitutions to types that support required operations or subtyping relationships. Unlike dynamic typing or casting through an untyped base type, generics preserve static type safety and eliminate unsafe runtime downcasts, though implementations balance compile-time code specialization against shared runtime representations.

    Common Forms

    • Type-Erased Generics: Validates type arguments during compilation and removes concrete type parameters from runtime representations (such as Java bytecode instances or transpiled JavaScript from TypeScript), avoiding code duplication while disallowing runtime checks on erased type arguments.

    • Monomorphized Generics: Generates specialized machine code or concrete definitions for each distinct combination of type arguments at compile time (as in Rust generics and C++ templates), enabling inlining and unboxed memory layouts at the cost of larger binaries and longer builds.

    • Reified Generics: Retains concrete type argument metadata at runtime alongside generic definitions—such as .NET generics in C# or Kotlin inline reified functions—supporting runtime type checks, reflection, and unboxed storage for value types.

    • Bounded Generics: Restricts type parameters using interface, protocol, or trait constraints (such as Rust where clauses, Go type constraints, or Java extends bounds) so generic implementations can safely invoke specific methods or operators on any conforming type.

    Example

    A Rust microservice defines a generic helper fn parse_event<T: DeserializeOwned>(payload: &[u8]) -> Result<T, serde_json::Error> so one ingestion pipeline can decode Kafka messages into distinct OrderCreated or PaymentSettled structs. When a consumer invokes parse_event::<OrderCreated>(&msg), the compiler monomorphizes the function for OrderCreated, verifies the DeserializeOwned trait bound, and catches invalid field access such as event.card_last4 at compile time.