No, there is no callback in your example.
A callback is when the function is passed as a parameter to another function - not the result of calling it, as you have above, but the function itself, to be called from within the receiver. e.g.:
Function Mensaje:String(f:String()) 'look at the parameter type
Return f() + "..." 'f is callable
End Function
Function Saludo:String()
Return "HOLA MUNDO"
End Function
Print Mensaje(Saludo) 'notice that Saludo is NOT called here Callbacks are useful because they let you pass functionality into other pieces of code. This means you can write code that is very generic. e.g. you can have a function that accepts an array and a callback, and loops over the array applying the callback to every element:
Function ProcessArray:Int[](arr:Int[], f:Int(_:Int))
Local ret:Int[arr.Length]
For Local k:Int = 0 Until arr.Length
ret[k] = f(arr[k])
Next
Return ret
End Function
Function square:Int(x:Int)
Return x * x
End Function
Function triple:Int(x:Int)
Return x * 3
End Function
Local a:Int[] = [1, 2, 3, 4, 5]
Local b:Int[] = ProcessArray(a, square) 'b = [1, 4, 9, 16, 25]
Local c:Int[] = ProcessArray(a, triple) 'c = [3, 6, 9, 12, 15] Because the callback changes depending on the parameter (instead of being a fixed function written into the body of the loop), you only need to write the array-traversal once, and can use it in many places without duplicating it. This is really good for things like sorting operations, where the traversal is complicated, so you want to abstract it, but the elementwise operation will change a lot (because arrays of different types of elements need a different comparator function).
|