Help subtyping with Parameters.jl

Could you please help me fix this subtyping error, I don’t know how Parameters.jl is interacting with the code:

using Parameters: @with_kw

abstract type AbstractVariogram{T<:Real,V} end

@with_kw struct GaussianVariogram{T<:Real,V} <: AbstractVariogram{T,V}
  range::T  = one(T)
  sill::V   = one(V)
  nugget::V = zero(V)
end

GaussianVariogram()
ERROR: UndefVarError: T not defined

In your example, would do you expect the type parameters (T and V) to be? You don’t give the constructor any information about them. Two easy fixes:

  1. Give the constructor types
julia> GaussianVariogram{Int,Float64}()
GaussianVariogram{Int64,Float64}
  range: Int64 1
  sill: Float64 1.0
  nugget: Float64 0.0
  1. Define the desired types for your default values:
julia> @with_kw struct GaussianVariogram{T<:Real,V} <: AbstractVariogram{T,V}
         range::T  = one(Float64)
         sill::V   = one(Int)
         nugget::V = zero(Int)
       end
GaussianVariogram

julia> GaussianVariogram()
GaussianVariogram{Float64,Int64}
  range: Float64 1.0
  sill: Int64 1
  nugget: Int64 0

Also, if you look at the src for Parameters.jl, the comments explain what the macro is doing: https://github.com/mauro3/Parameters.jl/blob/87ffb34adb3555fded8cfc2227d4defd22a38be7/src/Parameters.jl#L148

4 Likes

That is beautiful @ohsonice, I always miss the type information step. Thank you very much :slight_smile: