@head @title Intersection types @note This section is a stub. @end
Intersection types allow you to define multiple signatures for a single function, similar to function or method overloading in languages such as Java, C# and C++. Unlike the previous languages, Alore functions always have a single body. @h2 Intersection type basics
Specify an intersection type using the or keyword after a normal function signature, followed by another signature without the function name. This examples defines a function that can be called with either a Str or Int argument: @example def IncStr(x as Str) as Str or (x as Int) as Str if x is Str return Str(Int(x) + 1) else return Str((x as Int) + 1) end end IncStr('6') -- '7' IncStr(5) -- '6' @end
There a several things to note:
Alore standard libraries use intersection types in several places, most notably for arithmetic operators such as +. They allow the following code to type check: @example 2 * 3 -- Int * Int 2 * 1.1 -- Int * Float 2 * 'x' -- Int * Str @end @h2 Overlapping signatures
Signatures in intersection types must not be overlapping, unless they have identical return value types. Consider this example: @example def f(x as Int) as Int (x as Object) as Str ... end @end
When called with an Int argument, either of the signatures can match; they are overlapping. This would not be a problem if the return value types would be identical, but they are different (Int and Str). @h2 Interface methods and intersection types
If a class implements two interfaces with an identically-named method, you may be able to define an intersection type for the method that is compatible with both the interfaces.