Doing crazy stuff with generics

Hi all :slight_smile:

Why can’t I do the following:

julia> function crazy(T)
           if T == Int
               String
           elseif T == String
               Int
           else
               error("use Int or String")
           end
       end
crazy (generic function with 1 method)

julia> struct B{T <: Union{Int, String}}
           a::crazy(T)
       end
ERROR: use Int or String
Stacktrace:
 [1] error(s::String)
   @ Base .\error.jl:33
 [2] crazy(T::TypeVar)
   @ Main .\REPL[3]:7
 [3] top-level scope
   @ REPL[4]:1

you can’t call function here. more broadly, Julia doesn’t have dependent types, you can’t compute the type of a field based on type parameters

1 Like

You can sort of do this with GitHub - vtjnash/ComputedFieldTypes.jl: Build types in Julia where some fields have computed types but it would be great to have this work in base Julia too.

4 Likes