Skip to content

Order-dependent error in recursive data type constructor #42297

Closed
@tkf

Description

@tkf

The following definition of a recursive data type does not work in Julia 1.3 and later.

julia> mutable struct Node{T,V}
           value::V
           next::Union{Node{T,T},Node{T,Val{T}},Nothing}

           Node{T}(value) where {T} = new{T,typeof(value)}(value, nothing)
       end

julia> Node{Int}(1)
Node{Int64, Int64}(1, nothing)

julia> Node{Int}(Val{Int}())
ERROR: MethodError: Cannot `convert` an object of type Val{Int64} to an object of type Int64
Closest candidates are:
  convert(::Type{T}, ::Ptr) where T<:Integer at pointer.jl:23
  convert(::Type{T}, ::T) where T<:Number at number.jl:6
  convert(::Type{T}, ::Number) where T<:Number at number.jl:7
  ...
Stacktrace:
 [1] (Node{Int64, V} where V)(value::Val{Int64})
   @ Main ./REPL[1]:5

If I reboot julia and then evaluate Node{Int}(Val{Int}()) first, it does not throw but Node{Int}(1) now throws:

julia> Node{Int}(Val{Int}())
Node{Int64, Val{Int64}}(Val{Int64}(), nothing)

julia> Node{Int}(1)
ERROR: MethodError: Cannot `convert` an object of type Int64 to an object of type Val{Int64}

Julia 1.0.5 and 1.2.0 can handle construction in both orders. But in 1.3.1, 1.7.0-beta, and 1.8-DEV, I see the above order-dependent behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    regressionRegression in behavior compared to a previous versiontypes and dispatchTypes, subtyping and method dispatch

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions