Search code examples
juliaparametric-polymorphism

Parametric constructors


I am having some issues understanding the concept of parametric constructors in Julia. I am looking at the standard example in the Julia docs:

struct Point{T<:Real}
    x::T
    y::T
end

To my understanding, this means I can generate a Point-datatype with an input that is subtype of Real, i.e., AbstractFloat, AbstractIrrational, ..., Integer, Rational, ..., StatsBase.TestStat.

However, both of the examples below result in errors:

Point(Integer(12))
Point(Rational(12))

Why does the above fail given that both integer and rational are subtypes of real?


Solution

  • The type parameter goes inside the curly braces in the constructor call, just like it does in the struct definition:

    
    julia> Point{Integer}(12, 12)
    Point{Integer}(12, 12)
    
    julia> Point{Rational}(12, 10//3)
    Point{Rational}(12//1, 10//3)
    
    

    The arguments supplied are the values for the fields of the struct i.e. x and y. If the arguments are already of the type you want, you can leave out explicitly specifying the type parameter:

    julia> Point(12, 6)
    Point{Int64}(12, 6)
    
    julia> Point(12.0, 6.0)
    Point{Float64}(12.0, 6.0)
    
    
    julia> Point(12, 6.0) #no automatic type promotion happens though
    ERROR: MethodError: no method matching Point(::Int64, ::Float64)
    Closest candidates are:
      Point(::T, ::T) where T<:Real at REPL[1]:2
    Stacktrace:
     [1] top-level scope
       @ REPL[9]:1
    
    julia> Point{Float64}(12, 6.0) #unless you explicitly specify the type
    Point{Float64}(12.0, 6.0)