Constructors for different type parameters?


Is there a way to write a constructor for a type that has part of its parameter list specified?

For example, consider struct MyType{A,B} end. I would like to write a constructor for the type MyType{Int,B} where B i.e. where one of my type parameters is already known.

I’ve tried the following (and various different combinations):

struct MyType{A,B}
function MyType{Int, B}(x::B) where B

When I try to create an object of MyType, I get this:

julia> MyType{Int}(1)
ERROR: MethodError: no method matching MyType{Int64,B} where B(::Int64)

The strange thing is if I try to define a constructor with form similar to what crops up in the error message (i.e. something like function MyType{Int, B} where B(x::B) new() end I get a syntax error.

I’ve tried looking for related questions and I think this Defining a constructor for partially parameterized type is quite close to what I am looking for, but I can’t quite adapt it to my case.

Any suggestions will be helpful! :slight_smile:


Are you looking for something like this?

julia> struct MyType{A,B}        
         MyType{Int}(x) = new{Int,typeof(x)}() 

julia> MyType{Int}(3)

julia> MyType{Int}(3.)


Or more general

julia> struct MyType{A,B} end
julia> MyType{X}(y) where X = MyType{X,typeof(y)}()

julia> MyType{Float64}(1)


Yes! That is exactly what I wanted. Thank you very much :smile: