Optional arguments to inner type constructor



I am trying to implement a type with optional arguments to its inner constructor, like

type A
    function A(b; c = 1)
        new(b, c)

which works like a charm when I call A(2). However, when I add type information it breaks down:

type AT{T}
    function AT(b::T; c = 1)
        new(b, c)

gives a MethodError (falls back to convert, does not find right constructor).


This is unrelated to optional arguments. You are defining an inner constructor, i.e. a method for AT{T} in the second case which should be called as AT{Int}(1). Define a method for (::Type{AT}){T}(b::T; c = 1) if you want AT(1) to work. (Syntax might become simpler as current conflicting syntax get’s deprecated).


I see the problem now, thanks. I do not get the meaning of (::Type{AT}){T}, though. What does it mean exactly?


It means that you are defining a method for somthing of type Type{AT}, i.e. the object AT, and the method is parametrized with a type paremeter T.


Sorry for asking again, does “(::Type{AT}){T}” have a “name” or something? Is this syntax constructor-specific? Looks totally weird to me oO …

also, whats the advantage over defining an external constructor AT{T}(b::T; c = 1) = AT{T}(b::T, c) and leaving the inner constructor to default? I wanted to save the external constructor becuase it results in a lot of boiler-plate code with many fields.


You might also want to look at Parameters.jl. I think it does what you are looking for.


That’s even better than what I had in mind :wink: