3 ms·
In a static language, functions, classes, and types are often parametrized by other types. For example, with a function: imagine you wrote a `sum(array)` funct
by dunpeal 8y ago
In a static language, functions, classes, and types are often parametrized by other types.
For example, with a function: imagine you wrote a `sum(array)` function. In Ruby that's not a problem, because array can contain any types, as long as they support the + operator (aka duck typing). Any function can also return any type of object.
In a static language, however, an array that holds floats has a different type than an array that holds integers or an array that holds strings. The return value of the function sum() will also be different, depending on the type of the array, because if it's an array of floats, the sum will be a float.
So generics allow you to sort of implement duck-typing in static language:
T sum(array<T>) // Pseudocode
Now the sum function will take an array of any type T, and return a result of the same type T.
Similar idea for classes and other types. The classic example is a container. A linked-list in Ruby can contain any type or mixture a types, since the language is fully dynamic. However, in a static language, a linked-list of strings has a different type than a linked-list of ints. So you write something like (pseudocode):
class List<T>
{
T head_val() { return head.val; }
}
Now you write the List<T> class once, and use it for any type T, so it's DRY when you may have any number of types T that your program stores in a list.
- Exuma 8y agoAwesome, so this makes sense. So I guess people are against it because they like the explicit simple nature of Go rather than some sort of abstraction magic?
- dunpeal 8y agoI can't speak for all of them, but generics do tend to add a bunch of rules to a language, and make it more complex than before.