Passing functions as arguments: confusion with constructors

#1

Let’s say I have a type Foo, and I would like to pass its constructor as an argument to another function, bar, that only takes functions as arguments. How can I distinguish between the type, Foo, from its constructor when passing it to bar? That is, if bar has a signature bar(f::Function, ...) how can I call bar(Foo, ...) without running into problems? The naive approach seems to throw errors, because Foo is also a type.

#2

Functions are not the only thing that can be called in julia, there are also types and callable objects. The ::Function argument type is fairly worthless and the best imo is just to do duck typing. Have no argument type and just try to call it, if it can’t be called it will error.

2 Likes
#3

My actual use case is trying to use open(f, ...) with the CSV.File constructor, which doesn’t work because open is not duck typed :frowning:.

#4

Sounds like you should open an issue. :drum:

You can always do f(args...) = CSV.File(args...) and pass f.

1 Like
#5

Have you tried wrapping it in an anonymous function? As in

bar(x->Foo(x), ...)

or

bar((args...)->Foo(args...), ...)

This is basically the same as @kristoffer.carlsson’s approach, but a bit more compact.

#6

That’s what I ended up doing, though it turns out that closing the file handle on CSV.File is not a good idea.

Too bad Julia doesn’t have interfaces! Are there any plans to add such an idea? It would be great to have some sort of callable interface, or not have to resort to duck typing.