Type polymorphism
Last updated
Last updated
Classes in Luna can also take type parameters, making them polymorphic in some values. For an example, consider the previous definition of Vector
:
What if we needed a Vector
of Int
s? In the current approach, it would require us to create another class just for this purpose. We can, however, add a type parameter to the Vector
class:
Equipped with this definition, we can create vectors containing elements of any type, such as Real
s, Int
s, Bool
s etc.
It is also possible to implement methods that assume some additional properties of the type a
(such as supporting arithmetic operations, or having defined some other methods). Once you use such properties, Luna typechecker automatically keeps track of them and checks whether they are satisfied. For example:
The dotProduct
method will work with any elements supporting addition and multiplication, so using it with Int
s or Real
s is fine, while using it with Text
results in a type error.