`if foo isa Foo{K} where K; @show K; end`: `K` not defined

This has nothing to do with if and everything to do with where.

julia> foo isa Foo{K} where K
true

julia> K
ERROR: UndefVarError: `K` not defined

The reason that Foo{K} where K does not work is that it does not actually assign K as a variable. It’s only usable as a typevar within the expression it belongs to. As far as I know (which may be wrong) the parameter is only made available when where is used in a method definition (e.g., with function). I don’t have an explanation as to why.

I’m not aware of any responsible way to recover K from the type except for the get_k pattern you already mentioned.

ONE SHOULD NOT but one can get this particular parameter with typeof(foo).parameters[1]. This is absolutely discouraged and may break in any Julia version. It’s also very brittle to changes in Foo.

2 Likes