Sobes.tech
Junior

What are generics?

sobes.tech AI

Answer from AI

Generics are a mechanism in programming languages that allows defining classes, interfaces, and methods with a placeholder for types, enabling code to operate on objects of various types while providing compile-time type safety.

Main goals of using generics:

  • Type safety: The compiler checks types during compilation, preventing runtime errors.
  • Code reusability: The same class or method can work with different types.
  • Elimination of casts: No need for explicit casting, reducing errors.

Example in Java:

Without generics:

List list = new ArrayList();
list.add("string");
list.add(123);
String s = (String) list.get(0);
Integer i = (Integer) list.get(1);

With generics:

List<String> list = new ArrayList<>();
list.add("string");
// list.add(123); // Compile-time error
String s = list.get(0);

In Python, using the typing module:

from typing import List, TypeVar

T = TypeVar('T')

def get_first_element(data: List[T]) -> T:
    return data[0]

result_str = get_first_element(["apple", "banana"])
result_int = get_first_element([1, 2, 3])

Generics enable creating flexible, type-safe, and reusable code.