Type instability in parametric struct

I hate that this is silent. This is what often happens when you try to put function calls in annotations:

julia> struct Y{N}
           a::N
           b::(N+1)
       end
ERROR: MethodError: no method matching +(::TypeVar, ::Int64)

The definition actually immediately tries to execute the call, but most methods reasonably don’t work on TypeVar type parameters. No error was thrown by X and the annotation became ::Any because eltype(::TypeVar) actually reaches the fallback eltype(x) = Any method. I however have no good ideas for an error a struct definition could throw in general to catch these things, and function calls not involving TypeVar could be useful in annotations.

Your intent seemed to be enforcing a constraint at instantiation and trimming a “redundant” type parameter, but annotations can’t do that because methods are redefineable (and very little of Julia are the fixed intrinsics and builtins). Let’s say I instantiate a X{MyOnes}(MyOnes(), 1im), but then I redefine eltype(::Type{MyOnes}) = Bool and instantiate a X{MyOnes}(MyOnes(), true). Now X{MyOnes} has 2 instances with different structures, this can’t have a good implementation anymore. That second parameter is not actually redundant after all.

3 Likes