Fallback Constructor for All Subtypes

I have a series of structs that are all subtypes of the same abstract type. They can all be constructed with the same logic, but I’d like to have unique constructor names.

abstract type AbstractThing end

struct Thing1 <: AbstractThing
    val
end
struct Thing2 <: AbstractThing
    val
end

# what I'm trying to do
function (t::T)() where {T <: AbstractThing}
    t("blah")
end

Thing1()
# Thing1("blah")
Thing2()
# Thing2("blah")

But after several iterations of trying to define the function, I can’t seem to get it to define a function for all subtypes.
I’m aware that I could just do construct(::Type{T}) where {T <: AbstractThing} = T("blah"), but I like the ergonomics of using the normal constructor syntax using the types’ names.

Perhaps this is what you want:

function (T::Type{<:AbstractThing})()
    T("blah")
end
3 Likes