Optional arguments to inner type constructor


#1

Hi,

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

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

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

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

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


#2

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).


#3

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


#4

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.


#5

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

edit:
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.


#6

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


#7

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