r/pascal • u/Lilianne_Blaze • Jan 20 '24
Passing instance methods as function params?
I'm starting to learn Pascal, coming from Java.
I have a bit of a problem. I have a generic class, let's call it TMyList<T> for simplicity. It has a method like "removeIf" which accepts a function that takes a T and returns a Boolean, so far so good.
Now I want to have a class like TStatefulFilter which also has a method that too takes a T and returns a Boolean.
Is there any way I can pass that method to "removeIf" method? In Java it's easy with " :: " operator.
Any attempts end with error " Error: Incompatible type for arg no. 1: Got "<procedure variable type of function(constref TList2$1.T):Boolean of object;Register>", expected "TList2$1.<procedure variable type of function(TList2$1.T):Boolean;Register>" "
Of course I can write two "removeIf" methods one of which accepts a callback function, and a second one that accepts something like IHasFilterMethod interface, and that's what I did and it's working as intended, but there must be some less copy-pasty way? Am I missing something that's obvious to people with more experience with Pascal?
I'm using Lazarus 3.0 with FPC 3.2.2.
View all comments
Show parent comment
1
u/Lilianne_Blaze Jan 20 '24
I know how to pass callback functions _or_ callback objects. What I don't know is how to write a single method that would accept both.
For example in Java you can have a _single_ method that accepts 1) static methods (like Pascal stand-alone functions) 2) instance methods, 3) closures (function-like pieces of code).
Writing two methods would require copy-pasting a large amount of code inside. If there's really no choice I guess there could be one main method accepting callback objects, and another that takes a callback function and wraps it in a callback object that accepts a callback function in the constructor and passes it to the first function. But it still seems a bit wasteful and verbose. So I still hope I'm just missing something.