Functions
Crystal Generic Functions
Generic Functions
Crystal generic functions use type parameters for polymorphism.
What Are Generic Functions?
Generic functions in Crystal allow you to write flexible and reusable code by using type parameters. These parameters enable functions to operate on different data types while maintaining type safety. This approach is particularly useful for creating libraries or frameworks where the exact types might not be known at the time of writing the code.
Defining a Generic Function
To define a generic function in Crystal, you use angle brackets <>
to specify type parameters. These parameters act as placeholders for the actual types that will be provided when the function is called. Here is a basic example of a generic function:
In this example, the add
function takes two parameters, a
and b
, both of which are of type T
. The function returns a value of the same type. The T
is a type parameter that will be replaced by an actual type when the function is invoked.
Using Generic Functions
Once defined, you can use generic functions with different data types. Crystal's compiler will ensure that the types are compatible with the operations inside the function. Here's how you can use the add
function with different types:
As shown, the add
function can be used with integers, floats, and even strings, showcasing the flexibility provided by generic functions.
Constraints on Type Parameters
Sometimes, you might want to restrict the types that can be used with your generic function. Crystal allows you to add constraints to type parameters using the <
syntax. Here's an example:
In this example, the max
function is defined to work only with types that include the Comparable
module. This ensures that the >
operator can be used safely on the parameters a
and b
.
Benefits of Using Generic Functions
- Code Reusability: Generic functions allow you to write functions that can work with any data type, reducing code duplication.
- Type Safety: Despite their flexibility, generic functions in Crystal maintain strict type safety, catching errors at compile time.
- Improved Readability: With constraints, it's clear what kind of operations are expected on the parameters, making your code easier to understand.
Functions
- Functions
- Named Arguments
- Default Arguments
- Blocks
- Procs
- Closures
- Generic Functions