Methods
A method is a distinct function defined for a specific type of object. There may be methods that share the same name, but each pointing at different functions, depending on the type of the object on which they are invoked.
1
"string".length # String.length()
2
[1,2,3].length # Array.length()
Copied!
The methods can also be invoked using the prefix notation:
1
length("string")
2
length([1,2,3])
Copied!
The prefix and postfix notations can be used interchangeably:
1
log("string".length) # means: "string".length.log
2
length("string").log # =//=
3
log(length("string")) # =//=
Copied!
A method can be invoked using the prefix notation, even when a function with the same name is declared in the same scope. This is done by preceding the method with ::, as illustrated below:
1
func sqrt(n) { "sqrt of #{n} is #{n.sqrt}" }
2
3
say sqrt(42) # calls the `sqrt` function defined above
4
say ::sqrt(42) # calls the `Number.sqrt()` method
Copied!
Additionally, any alphanumeric method name can be used as an infix operator, by surrounding it with two backticks:
1
(1 `add` 2) # means: 1.add(2)
2
(Math `sum` (1,2,3)) # means: Math.sum(1,2,3)
Copied!
There is also support for calling a method which its name is not known until at run-time, which can be any expression that evaluates to a string:
1
say ( 50.(['+', '-'].rand)(30) ) # prints 20 or 80
Copied!
If a method is not found for a given object, Sidef will throw a run-time error.
Last modified 1yr ago
Copy link