Accessing the constructor of a type as a function

Is there any way that I can get the construction function of a struct?

What I want to do is the following:

I have a struct Foo and 2 Worker structs:

struct Foo
  worker_creator::Function
end

mutable struct HardWorker
  data::Integer
  overtime::Integer
  HardWorker(data = 10, overtime = 10) = new(data, overtime)
end

struct LazyWorker
  data::Integer
  slacktime::Integer
  absence::Integer
  LazyWorker(data = 0, slack time = 10, absence = 10) = new(data, slack time, absence)
end

I now want to create a Foo struct as follows:

foo1 = Foo(HardWorker)
foo2 = Foo(LazyWorker)

Can this be done? Or do I need to explicitly need to create a creator function?

Thanks in advance,
Stef

The type is the “constructor function”, however it’s not of type Function. Usually, if you want to type-constrain for anything callable, you can use Base.Callable which is the same as Union{Function, Type} for that reason.

4 Likes

Perhaps this is what you want?

struct Foo{T}
  worker :: T
end

mutable struct HardWorker
  data::Integer
  overtime::Integer
end


struct LazyWorker
  data::Integer
  slacktime::Integer
  absence::Integer
end

HardWorker(data = 10, overtime = 10) = HardWorker(data, overtime)

LazyWorker(data = 0, slacktime = 10, absence = 10) = 
	LazyWorker(data, slacktime, absence)

julia> Foo(HardWorker())
Foo{HardWorker}(HardWorker(10, 10))

Thanks! Although it’s not quite the solution I was looking for, it gave me new insights that will definitely come in handy later on.

1 Like