Conceptadvanced
Bounded generics
Also called bounded quantification, bounded polymorphism, constrained genericity, bounded type parameter, type constraint, trait bound, upper bound, where clause, F-bounded polymorphism.
A bound on a type parameter limits the type arguments to types with some operations, such as a compare method, so the generic code can use those operations and the compiler can check each call.
- Applies to
- core-languages
Idea
A generic function with a plain type parameter T knows nothing about its arguments, so it can only store them, pass them on and return them. To compare two items, add them or hash them, the function needs to know that T has that operation. A bound on the type parameter says so: T can be any type, but only a type that has the operation.
from typing import SupportsAbs
def total_abs[T: SupportsAbs[float]](items: list[T]) -> float:
return sum(abs(x) for x in items)
print(total_abs([-2, 3.5]))
print(total_abs.__type_params__[0].__bound__)
try:
total_abs(["a"]) # a type checker reports this call
except TypeError as e:
print(type(e).__name__)
5.5
typing.SupportsAbs[float]
TypeError
The bound SupportsAbs[float] says that each item must have an __abs__ method, so the body can call abs(x). A type checker rejects the call with a list of strings. Python itself does not check the bound, so the error comes from abs when the program runs.
How it works
A bound limits the type arguments. In Java, "There may be times when you want to restrict the types that can be used as type arguments in a parameterized type"1. The type parameter gets a bound, such as <T extends Number>, and the compiler rejects a call whose type argument is not a subtype of the bound. "Bounded quantification is an interaction of parametric polymorphism with subtyping."2
The body can use the operations of the bound. "In addition to limiting the types you can use to instantiate a generic type, bounded type parameters allow you to invoke methods defined in the bounds"1. Without a bound, the body can use only the operations of every type. In C#, "Without any constraints, the type argument could be any type. The compiler can only assume the members of System.Object"3.
The forms of bounds. Each language writes a bound in its own way:
- Java and TypeScript use
extends:<T extends Comparable<T>>in Java and<Type extends Lengthwise>in TypeScript4. Kotlin uses a colon, and "The most common type of constraint is an upper bound, which corresponds to Java's extends keyword"5. - C# uses a
whereclause:where T : IComparable<T>. "If client code uses a type that doesn't satisfy a constraint, the compiler issues an error."3 - Rust uses trait bounds,
T: PartialOrd, or awhereclause after the signature. "We can use trait bounds to specify that a generic type can be any type that has certain behavior."6 - Go uses an interface as the constraint: "A type constraint is an interface that defines the set of permissible type arguments for the respective type parameter and controls the operations supported by values of that type parameter"7. "Each type constraint specifies the permissible type arguments that calling code can use for the respective type parameter."8 A Go constraint can also be a union of types, such as
int64 | float648. - C++ uses concepts. "Each concept is a predicate, evaluated at compile time, and becomes a part of the interface of a template where it is used as a constraint"9.
- Python uses an upper bound on a type variable: "The upper bound of a type variable can be a concrete type, abstract type (ABC or Protocol), or even a union of types"10.
More than one bound. A type parameter can need two operations. In Java, "A type variable with multiple bounds is a subtype of all the types listed in the bound"1, written <T extends A & B>. Rust writes T: Display + Clone. In Kotlin, "Only one upper bound can be specified inside the angle brackets"5, so two bounds go in a where clause.
F-bounded polymorphism. A bound can mention the type parameter itself, as in <T extends Comparable<T>>. Then T must be comparable to T, and not only to some other type. This is "F-bounded quantification or recursively bounded quantification, introduced in 1989"2. The Java tutorial uses this bound for a method that counts the items greater than a given item11. The class Enum in Java has the declaration class Enum<E extends Enum<E>> and implements Comparable<E>, so "Enum constants are only comparable to other enum constants of the same enum type"12.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Absent | C has no type parameters. Generic code uses void pointers or macros, and the compiler cannot check a bound. |
| C# | Native | |
| JavaScript | Does not apply | JavaScript has no static types and no type parameters, so there is nothing to bound. |
| TypeScript | Native | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | A Kotlin type parameter can have an upper bound, such as Comparable<T> after a colon, and a where clause gives more than one bound. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | A query has no type parameters. |
| Bash | Does not apply | Bash has no types for its values. |
| PowerShell | Absent | A PowerShell script can use the generic types of .NET, but it cannot declare its own type parameters or their bounds. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no types of values. |
| CSS | Does not apply | CSS has no types in this sense. |
| Regular expressions | Does not apply | A regular expression has no types. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | an upper bound in [T: Bound] or TypeVar("T", bound=...), for static checkers |
| JavaScript | n/a | the language has no type parameters |
| TypeScript | native | <T extends Bound> |
| Java | native | <T extends Bound> and <T extends A & B>; wildcards ? extends Bound |
| Kotlin | native | <T : Bound> and a where clause |
| C# | native | where T : Bound, with special constraints such as struct, class and new() |
| Go | native | an interface as the constraint, such as cmp.Ordered, with unions of types |
| Rust | native | trait bounds T: Trait and where clauses |
| C | absent | the language has no type parameters |
| C++ | native | concepts and requires clauses on templates |
| Bash | n/a | the language has no types |
| PowerShell | absent | a script cannot declare its own type parameters |
| SQL | n/a | a query has no type parameters |
| Regex | n/a | a pattern has no types |
| HTML | n/a | HTML has no types |
| CSS | n/a | CSS has no types of this kind |
In Java, C#, Kotlin and TypeScript, a bound is a supertype: the type argument must be a subtype of it. In Rust, a bound is a trait, and a type satisfies it when an impl of the trait exists. In Go, a bound is an interface that can also list types. In C++, a concept is a test on the type that the compiler evaluates.
The example files show these forms. Python shows a Protocol as the bound. TypeScript shows a bound with a length property. Java shows Comparable<T> and two bounds. C# shows a where clause with IComparable<T> and new(). Go shows cmp.Ordered and a constraint with a union. Rust shows trait bounds, a where clause and the error for a type without the trait. C++ shows a concept and a requires clause.
from dataclasses import dataclass
from typing import Protocol
class HasArea(Protocol):
def area(self) -> float: ...
@dataclass
class Square:
side: float
def area(self) -> float:
return self.side * self.side
@dataclass
class Rect:
w: float
h: float
def area(self) -> float:
return self.w * self.h
def largest[T: HasArea](shapes: list[T]) -> T:
return max(shapes, key=lambda s: s.area())
print(largest([Square(2), Square(3)]))
print(largest([Rect(1, 5), Rect(2, 2)]))
Square(side=3)
Rect(w=1, h=5)
- Verdict: native.
[T: HasArea]givesTthe upper boundHasArea, aProtocol. A type checker accepts any type with anareamethod, and the result has the type of the argument,SquareorRect. Python does not check the bound when the program runs.
#include <concepts>
#include <iostream>
#include <string>
#include <vector>
template <typename T>
concept Shape = requires(const T& s) {
{ s.area() } -> std::convertible_to<double>;
};
struct Square {
double side;
double area() const { return side * side; }
};
template <Shape S>
double total_area(const std::vector<S>& shapes) {
double sum = 0;
for (const auto& s : shapes) {
sum += s.area();
}
return sum;
}
template <typename T>
requires std::totally_ordered<T>
const T& larger(const T& a, const T& b) {
return a < b ? b : a;
}
int main() {
std::cout << total_area(std::vector<Square>{{2}, {3}}) << "\n";
std::cout << larger(3, 9) << " " << larger(std::string("pear"), std::string("apple")) << "\n";
std::cout << std::boolalpha << Shape<Square> << " " << Shape<int> << "\n";
}
13
9 pear
true false
- Verdict: native.
Shapeis a concept: a type meets it whens.area()gives a value that converts todouble.template <Shape S>andrequires std::totally_ordered<T>are two ways to put a concept on a template.Shape<int>isfalse, so a call oftotal_areawith a vector ofintdoes not compile.
import java.util.List;
public class Main {
// An F-bound: T must be comparable with T.
static <T extends Comparable<T>> T max(List<T> items) {
T best = items.get(0);
for (T x : items) {
if (x.compareTo(best) > 0) {
best = x;
}
}
return best;
}
// Two bounds: a class first, then an interface.
static <T extends Number & Comparable<T>> double maxAsDouble(List<T> items) {
return max(items).doubleValue();
}
enum Size { SMALL, MEDIUM, LARGE }
public static void main(String[] args) {
System.out.println(max(List.of(3, 9, 4)));
System.out.println(max(List.of("pear", "apple")));
System.out.println(max(List.of(Size.MEDIUM, Size.SMALL)));
System.out.println(maxAsDouble(List.of(2, 7)));
}
}
9
pear
MEDIUM
7.0
- Verdict: native.
<T extends Comparable<T>>letsmaxcallcompareTo. An enum works too, becauseEnum<E extends Enum<E>>implementsComparable<E>.<T extends Number & Comparable<T>>has two bounds, so the body can calldoubleValueandcompareTo.
using System;
using System.Collections.Generic;
Console.WriteLine(Bounds.Max(new[] { 3, 9, 4 }));
Console.WriteLine(Bounds.Max(new[] { "pear", "apple" }));
var list = Bounds.MakeAndFill<List<int>>(3);
Console.WriteLine(list.Count);
static class Bounds
{
public static T Max<T>(IEnumerable<T> items) where T : IComparable<T>
{
var best = default(T);
var first = true;
foreach (var x in items)
{
if (first || x.CompareTo(best!) > 0)
{
best = x;
first = false;
}
}
return best!;
}
// Two constraints: an interface and a parameterless constructor.
public static C MakeAndFill<C>(int n) where C : ICollection<int>, new()
{
var c = new C();
for (var i = 0; i < n; i++)
{
c.Add(i);
}
return c;
}
}
9
pear
3
- Verdict: native.
where T : IComparable<T>letsMaxcallCompareTo.where C : ICollection<int>, new()letsMakeAndFillcreate aCand callAdd.
interface Lengthwise {
length: number;
}
function longest<T extends Lengthwise>(a: T, b: T): T {
return b.length > a.length ? b : a;
}
function maxBy<T, K extends number | string>(items: T[], key: (x: T) => K): T {
let best = items[0];
for (const x of items) {
if (key(x) > key(best)) best = x;
}
return best;
}
console.log(longest("ox", "cat"));
console.log(longest([1, 2, 3], [4]));
console.log(maxBy([{ n: "a", age: 30 }, { n: "b", age: 41 }], (p) => p.age).n);
cat
[ 1, 2, 3 ]
b
- Verdict: native.
T extends Lengthwiseaccepts strings and arrays, because both have alengthproperty.K extends number | stringlimits the key to types that>can compare. The checker removes the bounds before the program runs.
package main
import (
"cmp"
"fmt"
)
// Number is a constraint: a union of types.
type Number interface {
~int | ~int64 | ~float64
}
func Max[T cmp.Ordered](items []T) T {
best := items[0]
for _, x := range items[1:] {
if x > best {
best = x
}
}
return best
}
func Sum[T Number](items []T) T {
var total T
for _, x := range items {
total += x
}
return total
}
type Celsius float64
func main() {
fmt.Println(Max([]int{3, 9, 4}), Max([]string{"pear", "apple"}))
fmt.Println(Sum([]Celsius{1.5, 2.5}), Sum([]int64{1, 2, 3}))
}
9 pear
4 6
- Verdict: native.
cmp.Orderedis a constraint from the standard library, soMaxcan use>.Numberlists types, soSumcan use+=. The~letsCelsius, whose underlying type isfloat64, meet the constraint.
use std::fmt::Display;
fn largest<T: PartialOrd + Copy>(items: &[T]) -> T {
let mut best = items[0];
for &x in items {
if x > best {
best = x;
}
}
best
}
fn show_pair<T, U>(a: T, b: U) -> String
where
T: Display,
U: Display + Clone,
{
format!("{a} and {b}")
}
fn main() {
println!("{}", largest(&[3, 9, 4]));
println!("{}", largest(&['x', 'b']));
println!("{}", show_pair(1.5, "two"));
}
9
x
1.5 and two
This code does not compile, on purpose.
fn largest<T: PartialOrd + Copy>(items: &[T]) -> T {
let mut best = items[0];
for &x in items {
if x > best {
best = x;
}
}
best
}
struct Point {
x: i32,
}
fn main() {
let p = largest(&[Point { x: 1 }]);
println!("{}", p.x);
}
- Verdict: native.
T: PartialOrd + Copylets the body compare and copy the items. Thewhereclause puts the bounds ofshow_pairafter the signature.Pointdoes not implementPartialOrdorCopy, so the second program does not compile.
Variations and related ideas
- Bounded wildcards. Java also puts bounds on the type argument of a variable: "You can use an upper bounded wildcard to relax the restrictions on a variable"13. A
List<? extends Number>can be aList<Integer>or aList<Double>. See subtyping. - Bounds that select the code. In C++, a constraint "can be used to select the most appropriate function overloads and template specializations"9. In Rust, an
implwith a bound applies to every type that meets it: "Implementations of a trait on any type that satisfies the trait bounds are called blanket implementations"6. - Constraints that are not subtypes. C# has constraints such as
struct,class,notnullandnew(), which ask for a kind of type or a constructor3. Python can constrain a type variable to a fixed list:TypeVar('A', str, bytes)"Must be exactly str or bytes"10.
Pitfalls
- A bound that is too weak. A bound that does not mention
Tlets the function take two items of different types. With<S extends Comparable>, Java accepts a string and an integer in one call, and the program "Throws java.lang.ClassCastException at runtime"2. Use the F-bound<T extends Comparable<T>>. - Long signatures. "Using too many trait bounds has its downsides."6 With many type parameters, the bounds fill the space between the name of the function and its parameters, and the signature is hard to read. Rust, Kotlin and C# let you move the bounds to a
whereclause after the signature. - The order of bounds in Java. "If one of the bounds is a class, it must be specified first."1 If
Ais a class andBandCare interfaces,<T extends B & A & C>is a compile error1. - Errors inside templates. Without a concept, a C++ template fails only when the compiler makes its body for one type, and the message can point deep inside the template. With concepts, "Violations of constraints are detected at compile time, early in the template instantiation process, which leads to easy to follow error messages"9.
- Bounds that are not checked. In Python and TypeScript, only the type checker checks the bounds. A Python program runs a call that breaks a bound, and the error, if any, comes later.
History
Bounded quantification "has traditionally been studied in the functional setting of System F<:"2. F-bounded quantification was introduced in 1989, in a paper by Canning, Cook, Hill, Mitchell and others2. The Java standard library uses an F-bound in the declaration of Enum12, and Java, C#, Kotlin, Rust, Go and C++ all have a way to write a bound on a type parameter.
References
- Bounded Type Parameters, The Java Tutorials, Whole page
- Bounded quantification, Wikipedia, Introduction; F-bounded quantification
- Constraints on type parameters, C# programming guide, Introduction
- Generics, The TypeScript Handbook, Generic Constraints
- Generics, Kotlin documentation, Upper bounds
- Traits, The Rust Programming Language, Trait Bound Syntax; Clearer Trait Bounds with where Clauses; Using Trait Bounds to Conditionally Implement Methods
- The Go Programming Language Specification, Type constraints
- Tutorial: Getting started with generics, Go documentation, Add a generic function to handle multiple types
- Constraints and concepts, C++ reference, cppreference.com, Introduction; Concepts
- typing, Python 3.14 documentation, TypeVar
- Generic Methods and Bounded Type Parameters, The Java Tutorials, Whole page
- Class Enum, Java SE 21 API, Class declaration
- Upper Bounded Wildcards, The Java Tutorials, Whole page
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag K0A8GB Edit this page History Report an error Markdown