Back to Examples
Generic Functions
IntermediateLearn how to write reusable, type-safe code using Tea's powerful generic system with compile-time specialization.
Basic Generic Function
generic_first.tea
# Generic function to get first element
def first<T>(arr: Array<T>) -> T
arr[0]
end
# Works with any type
var numbers = [1, 2, 3]
var names = ["Alice", "Bob"]
print(first(numbers)) # 1
print(first(names)) # "Alice"Generic with Type Constraints
generic_comparable.tea
# Generic function with constraint
def max<T: Comparable>(a: T, b: T) -> T
if a > b
a
else
b
end
end
print(max(10, 20)) # 20
print(max("apple", "banana")) # "banana"Generic Class
generic_stack.tea
# Generic Stack implementation
class Stack<T>
var items: Array<T>
def init()
@items = []
end
def push(item: T)
@items.append(item)
end
def pop() -> T
@items.pop()
end
def size() -> Int
@items.length
end
end
# Use with integers
var int_stack = Stack<Int>.new()
int_stack.push(1)
int_stack.push(2)
print(int_stack.pop()) # 2
# Use with strings
var str_stack = Stack<String>.new()
str_stack.push("hello")
str_stack.push("world")
print(str_stack.pop()) # "world"Key Concepts
- 1Type Parameters
Use
<T>to define generic type parameters that can be replaced with any type - 2Type Constraints
Restrict generic types with constraints like
T: Comparableto ensure required operations - 3Compile-Time Specialization
Tea generates specialized versions of generic code for each type used, ensuring optimal performance
- 4Type Safety
Generics provide compile-time type checking, preventing type errors at runtime