Stream: helpdesk (published)

Topic: Changing value types for subtypes


view this post on Zulip Spencer Breiner (Aug 06 2021 at 00:17):

I am having some trouble getting the typing working for some code that involves a parametric abstract Foo{T} type with several concrete subtypes Bar1{T}, Bar2{T}, ...

The type parameter is intended as a value (e.g., Symbol) used for dispatch and otherwise is unused. I would like to be able to override the parameter as needed by calling Foo{S} on a value x::Foo{T}, but I need this to call the correct subtype constructor.

I can do this for each subtype individually, e.g.,

Foo{S}(x::Bar1{T}) where {S,T} = Bar1{S}(...something with x...)

Instead, I would prefer to do this all at once by introducing a type parameter for the subtype. I tried the following but got errors either way :

Foo{S}(x::Bar{T}) where {S,T,Bar{T}<:Foo{T}} = Bar{S}(...something with x...)

I get: Invalid type parameter name Bar{T}

Foo{S}(x::Bar{T}) where {S,T,Bar<:Foo} = Bar{S}(...something with x...)

I get: TypeError:... expected UnionAll, got a value of type TypeVar

Any suggestions for the right syntax or alternate approaches are appreciated. Thanks!


Last updated: Nov 22 2024 at 04:41 UTC