Multiple dispatch
Multiple dispatch allows us to declare multiple variants of the same function or method, each working only with a certain type of arguments.
For example, if we declare two functions with the same name, but with different types of parameters, Sidef will decide automatically which function to call:
1
func foo(Number a) {
2
say a
3
}
4
5
func foo(String a) {
6
say a
7
}
8
9
foo(1234) # calls the first function
10
foo("bar") # calls the second function
Copied!
The functions are checked in the order in which they are declared:
1
func foo(Array a) { ... } # works with an array
2
func foo(Hash h) { ... } # works with an hash
3
func foo(any) { ... } # works with anything else
Copied!
It also works with methods:
1
class Example {
2
method foo(Number n, String s) {
3
say "first"
4
}
5
6
method foo(Array a) {
7
say "second"
8
}
9
}
10
11
var obj = Example()
12
obj.foo(1234, "foo") # calls the first method
13
obj.foo([1,2,3]) # calls the second method
Copied!
Last modified 1yr ago
Copy link